Skip to content

Instantly share code, notes, and snippets.

@mizmay
Forked from crowding/unicode_ggplot2.R
Created April 21, 2013 23:07
Show Gist options
  • Save mizmay/5431447 to your computer and use it in GitHub Desktop.
Save mizmay/5431447 to your computer and use it in GitHub Desktop.
#negative numbers for "symbol" will be interpreted as Unicode values.
#But you must use a fint that supprots the symbols you want.
dataset <- chain(1:16, expand.grid(x=., y=.), mutate(shape=seq_along(x)))
print(ggplot(dataset) + aes(x=x, y=y, shape=factor(shape))
+ geom_point()
+ discrete_scale("shape", "manual", name="shape", palette=function(x) -seq(0x25A0L, length=x))
+ theme(legend.position="none")
)
grid.gedit("geom_point.points", gp=gpar(fontfamily="MS Gothic", fontsize=14))
##or using grobs to skip the first printing
grid.newpage()
gr <- ggplotGrob(ggplot(dataset) + aes(x=x, y=y, shape=factor(shape))
+ geom_point()
+ discrete_scale("shape", "manual", name="shape", palette=function(x) -seq(0x25A0L, length=x))
+ theme(legend.position="none")
)
#https://groups.google.com/d/msg/ggplot2/cnVDSyobPy4/5U8ky3FPtHwJ
editGtable <- function(gt, idx, ...) {
if (is.character(idx))
idx <- which(gt$layout$name == idx)
gt$grobs[[idx]] <- editGrob(gt$grobs[[idx]], ...)
gt
}
gr <- editGtable(gr, "panel", "geom_point.points", grep=TRUE, global=TRUE,
gp=gpar(fontfamily="MS Gothic", fontsize=14))
grid.newpage()
grid.draw(gr)
#Realistic example with a custon Unicode character scale.
fake.data <- chain(expand.grid(x=seq(-1,1,length=12),
g=0:4),
mutate(p = (rbinom(length(x), 50,
plogis(x, g/5-0.5, (5+g)/20))
)/50,
g = factor(g)))
ggp <- ggplot(fake.data) + aes(x=x, y=p, shape=g) + geom_point()
#custom scale
shape_sequence <- -rev(c(-16, -17, 0x2726L, 0x2605L,
0x2736L, 0x2737L, 0x2739L, 0x273AL))
shape_chooser <- function(n) {
shape_sequence[seq(floor(length(shape_sequence)-n)/2+1, length=n)]
}
custom_shape_scale <-
list(
discrete_scale("shape", "manual",
palette=shape_chooser, labels=prettyprint)
)
#edit to set the point font.
gr <- ggplotGrob(ggp + custom_shape_scale)
font <- gpar(fontfamily="MS Gothic", fontsize=14)
gr <- editGtable(gr, "panel", "geom_point\\.points",
grep=TRUE, global=TRUE, gp=font)
grid.draw(gr)
#edit the legend to display the font. I give up. This is impossible, or
#at least very hard when gtable does not implkement gTree or gedit
#functions.
keys <- grid.get("guide.box", grep=TRUE)$grobs[[1]]$grobs
lapply(keys, function(x) {
if ("points" %in% class(x))
x <- editGrob(x, gp=font)
x
}) -> keys
#and then how to stuff them back in???
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment