Editing raw grid objects from a ggplot - janeshdev/ggplot2 GitHub Wiki
Editing raw Grid objects from a ggplot
- save the plot as a grob
- locate the particular grob in the gTree
- call grid.edit() with the gPath constructed from the information of step #2
A simple example goes like this, (adpated from r-help, http://finzi.psych.upenn.edu/Rhelp08/2009-May/199976.html)
library(ggplot2)
p <- # minimal example
qplot(0,0, geom="blank")+ annotate("text",0,0,label="alpha")
p
g <- # store the plot as a grob
ggplotGrob(p)
# structure of the grob
# grid.ls(g) # rather large!
# find a particular grob in the gTree
# grid.ls(grob=F, view=T)
grid.ls(getGrob(g,"texts", grep = T))
grid.edit(gPath("texts.gTree", "GRID.text"), grep=TRUE,
gp=gpar(col="pink"))
grid.edit(gPath("texts.gTree", "GRID.text"), grep=TRUE,
label=expression(alpha^2), gp=gpar(col="red"))
Another example (removing either the x or y major/minor gridlines):
data <- data.frame(Name = c("A","B","C","D","E","F","G","H"), y = c(100,200,300,400,200,300,400,350))
# you have to print before grob-ing
ggplot(data,aes(x=Name,y=y)) + geom_bar()
# locate the lines
g <- # store the plot as a grob
ggplotGrob(p)
grid.ls(g)
#notice
#...
#panel-3-3
# grill.gTree.383
# panel.background.rect.374
# panel.grid.minor.y.polyline.376
# panel.grid.minor.x.polyline.378
# panel.grid.major.y.polyline.380
# panel.grid.major.x.polyline.382
grid.remove(gPath("GRID.gTree","layout","panel","grill.gTree","panel.grid.minor.x.polyline"),grep=T)
grid.remove(gPath("GRID.gTree","layout","panel","grill.gTree","panel.grid.major.x.polyline"),grep=T)
grid.remove(gPath("GRID.gTree","layout","panel","grill.gTree","panel.grid.major.y.polyline"),grep=T)
Note that ggsave() seems to discard these edits, so wrap with png()/pdf() and dev.off()