Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set limits for axes in ggplot2 R plots?

Tags:

plot

r

ggplot2

I plot the following:

library(ggplot2)      carrots <- data.frame(length = rnorm(500000, 10000, 10000)) cukes <- data.frame(length = rnorm(50000, 10000, 20000)) carrots$veg <- 'carrot' cukes$veg <- 'cuke' vegLengths <- rbind(carrots, cukes)  ggplot(vegLengths, aes(length, fill = veg)) +  geom_density(alpha = 0.2) 

Now say, I only want to plot the region between x=-5000 to 5000, instead of the entire range.

How can I do that?

like image 769
David B Avatar asked Aug 31 '10 07:08

David B


People also ask

How do I change axis limits 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.

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.

What is ggplot2 scale?

Scales in ggplot2 control the mapping from data to aesthetics. They take your data and turn it into something that you can see, like size, colour, position or shape. They also provide the tools that let you interpret the plot: the axes and legends.


2 Answers

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000)) 

or

coord_cartesian(xlim = c(-5000, 5000))  

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000) 

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

like image 186
midtiby Avatar answered Sep 27 '22 20:09

midtiby


Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400)) 

This just alters the visible range (i.e. doesn't remove data points).

like image 26
Bill Avatar answered Sep 27 '22 20:09

Bill