Skip to content

Editing raw grid objects from a ggplot

jameshowison edited this page Nov 27, 2010 · 7 revisions

Editing raw Grid objects from a ggplot

  1. save the plot as a grob
  2. locate the particular grob in the gTree
  3. 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)) 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("panel.grid.minor.x.polyline",grep=T) grid.remove("panel.grid.major.x.polyline",grep=T) grid.remove("panel.grid.minor.y.polyline",grep=T)

Note: The ggplot2 wiki is no longer maintained, please use the ggplot2 website instead!

Clone this wiki locally