Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture and manipulate ggplot2 default axis values

Tags:

r

ggplot2

I want to capture the default axis breaks from ggplot and transform them with prettyNum(). The code below works, but it creates the same plot twice, so it seems like a hack. Can the default values be captured with waiver()?

vec <- c(10^seq(-3,3,1))
foo.df <- data.frame("x"=vec,"y"=vec)
p <- ggplot(foo.df, aes(x,y)) + geom_point() +
  scale_x_log10() +
  scale_y_log10()

y_breaks <- ggplot_build(p)$layout$panel_params[[1]]$y.minor_source


ggplot(foo.df, aes(x,y)) + geom_point() +
  scale_x_log10() +
  scale_y_log10(breaks = 10^y_breaks, labels = prettyNum(10^y_breaks))
like image 290
Mark R Avatar asked Nov 24 '25 04:11

Mark R


1 Answers

The labels argument in scale_y_log10 can take a function, so you don't have to know the specific values of the default breaks. The function you pass to labels will transform the labels, whatever the break values happen to be. For example:

ggplot(foo.df, aes(x,y)) + geom_point() +
  scale_x_log10() +
  scale_y_log10(labels=prettyNum)

However, in your example, you're accessing the locations of the minor breaks, rather than the major breaks, so you're effectively turning the default minor breaks into custom major breaks. In that case, you can extract the minor breaks if you assign the initial plot to p, as you've done in your example, and then do the following, where we've used the layer_scales function to extract the locations of the minor breaks:

p + 
  scale_y_log10(breaks=10^layer_scales(p)$y$get_breaks_minor(),
                labels=prettyNum)
like image 151
eipi10 Avatar answered Nov 25 '25 19:11

eipi10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!