How to change axis labels in ggplots list?

I am creating a list of ggplots to make an animation. I want to select a shortcut along the x axis, and the position of this selection changes over different frames of the animation.

Here is an example plot. The first axis mark should be highlighted in the first frame, and the second in the second frame.

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 ) ) } 

Unfortunately, it seems that x_label_cols is evaluated when the chart is printed, and not when it is created, so both frames highlight the second label. Therefore, print(p_list[[1]]) not display correctly.

How do I get different colors of axis labels for each graph in the list?

+4
source share
1 answer

Why not configure options within saveGIF() ? As far as I know, opts() works the same way as options() , but then specifically for ggplot2. Thus, in your code you set the parameters twice, but only print the graphs after the last parameter change. Therefore, you must include the parameter change in the code run in saveGIF() .

This code does this 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)) ) }) ) 

It gives:

enter image description here

+4
source

Source: https://habr.com/ru/post/1346709/


All Articles