开发者

How do you change the axis labels in a list of ggplots?

I'm creating a list of ggplots in order to make an animation. I want to highlight a label on the x-axis, and the position of this highlight changes over the different frames of animation.

Here's a sample plot. The first axis label should be highlighted in frame one, and the second in frame two.

p <- ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_boxplot() 
p_list <- list()

for(i in 1:2)  
{
  x_label_cols <- rep("grey50", 3)
  x_label_cols[i] <- "red"
  p_list[[i]] <- p + 
    opts(
      axis.text.x = theme_text(
        colour = x_label_cols
      )
    )
}

Unfortunate开发者_开发技巧ly, it seems that x_label_cols is evaluated when the plot is printed, not when it is created, so both frames have the second label highlighted. Thus print(p_list[[1]]) displays incorrectly.

How do I get different axis label colours for each plot in the list?


Why not adjust the opts within saveGIF()? As far as I know, opts() works just like options(), but then specifically for ggplot2. So in your code you set the options twice, but only print the graphs after the last change of the options. Hence, you have to include the options change in the code run within saveGIF().

This code does it for me :

p <- ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot()

saveGIF(
  sapply(1:2,function(x){
      x_label_cols <- rep("grey50", 3)
      x_label_cols[x] <- "red"
      print(p + 
        opts(axis.text.x = theme_text(colour = x_label_cols))
      )
  })
)

Gives :

How do you change the axis labels in a list of ggplots?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜