Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set axis ranges in ggplot2 when using a log scale?

Tags:

r

ggplot2

I have a time series of data where the measurements are all integers between 1e6 and 1e8: website hits per month. I want to use ggplot2 to chart these with points and lines, but mapping the measurements to a log scale. Something like this:

qplot(month, hits, data=hits.per.month, log="y")

When I do that, ggplot seems to set the scale from 1e6 to 1e8. I want it to scale from 0 to 1e8. The natural way of doing this seems to have no affect on the output:

qplot(month, hits, data=hits.per.month, log="y", ylim=c(0, 100000000))

I can get the picture I want by transforming hits before it reaches qplot, but that changes the labels on the axis:

qplot(month, log10(hits), data=hits.per.month, log="y", ylim=c(0, 8))

I also tried various combinations with scale_y_log10, but had no luck.

So, how do I set the Y axis range when using a log scale in ggplot2?

like image 560
jml Avatar asked Feb 10 '12 17:02

jml


People also ask

How do I change the y axis values in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.

How do I change the axis range in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

What does scale_y_log10 do in GGPlot?

GGPlot Log Scale Transformation An other possibility is the function scale_x_log10() and scale_y_log10(), which transform, respectively, the x and y axis scales into a log scale: base 10. Note that, the scale functions transform the data. If you fit anything to the data it would probably change the fitted values.


1 Answers

Much of ggplot2 is simply clearer to me if one doesn't use qplot. That way you aren't cramming everything into a single function call:

df <- data.frame(x = 1:10,                  y = seq(1e6,1e8,length.out = 10))  ggplot(data = df,aes(x = x, y =y)) +      geom_point() +      scale_y_log10(limits = c(1,1e8)) 

enter image description here

I'm going to assume you didn't really mean a y axis minimum of 0, since on a log scale that, um, is problematic.

like image 181
joran Avatar answered Oct 08 '22 15:10

joran