Search code examples
rggplot2axis-labels

Break points not behaving with scale_y_continuous()


I'm trying to plot some data where the y-values are large:

p <- seq(0.1, 0.9, 0.1)
cost <- 1/(p^2)^15 * 15 * 0.1
data <- data.frame(x=p, y=cost)
ggplot(data, aes(x=x, y=y)) + 
  geom_point(shape=18, color="blue")+
  scale_y_continuous(name="Cost", breaks=c(0, 1e5, 1e10, 1e15, 1e20, 1e25, 1e30))

When specifying the breakpoints like this, however, all the data points except the first and largest y-value are aligned with the line y=0.

See: ggplot output

Suggestions?


Solution

  • Your best bet is to rescale your data, such as here with the logarithm. You could just denote this in the labeling of your graph, and still provide un-scaled y-axis labels.

    breaks = c(0, 1e5, 1e10, 1e15, 1e20, 1e25, 1e30)
    
    ggplot(data, aes(x=x, y=log(y))) + 
      geom_point(shape=18, color="blue")+
      scale_y_continuous(name = "Cost", 
                         breaks = log(breaks),
                         labels = breaks)
    

    Even simpler, a bit rusty:

    ggplot(data, aes(x=x, y=y)) + 
      geom_point(shape=18, color="blue")+
      scale_y_continuous(name="Cost",
                         breaks = c(0, 1e5, 1e10, 1e15, 1e20, 1e25, 1e30),
                         trans = "log")