Mark R
Mark R

Reputation: 1009

How can I capture and manipulate ggplot2 default axis values

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

Upvotes: 3

Views: 405

Answers (1)

eipi10
eipi10

Reputation: 93821

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)

Upvotes: 3

Related Questions