Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use coord_carteisan and coord_flip together in ggplot2

Tags:

r

ggplot2

I have some weird behavior from ggplot. Here's a MWE:

the_data <- data.frame(
   myx <- 1:10,
  lower <- rnorm(10,-5,1),
  mean <- rnorm(10,0,.5),
  upper <- rnorm(10,5,1))
the_data2 <- data.frame(
  myx <- 1:10,
  lower <- rnorm(10,-5,1),
  mean <- rnorm(10,0,.5),
  upper <- rnorm(10,5,1))

Now, I want to construct a plot where the end product will have a point for the mean, and a line drawn from lower to uppper. But I want these lines to be horizontal. I also want to "zoom in" on the graph so that only values from -1 to 1 are shown. I need to use coord_cartesian because if I use ylim it drops the data points that are outside the graph, which messes up the lines. But when I run:

ggplot() +
  geom_pointrange(aes(x=myx, y=mean, ymin=lower, ymax=upper), data=the_data) +
  geom_pointrange(aes(x=myx, y=mean, ymin=lower, ymax=upper), data=the_data2) +
  coord_cartesian(ylim = c(-1, 1)) +
  coord_flip() 

it doesn't apply the "zooming" and switching the two arguments:

ggplot() +
  geom_pointrange(aes(x=myx, y=mean, ymin=lower, ymax=upper), data=the_data) +
  geom_pointrange(aes(x=myx, y=mean, ymin=lower, ymax=upper), data=the_data2) +
  coord_flip() +
  coord_cartesian(ylim = c(-1, 1)) 

applys the zooming but not the flipping. What's going on here?

like image 466
Alex Avatar asked Oct 28 '15 14:10

Alex


People also ask

What does Coord_cartesian do in R?

coord_cartesian() contains the arguments xlim and ylim . These arguments control the limits for the x- and y-axes and allow you to zoom in or out of your plot.

What is Coord_flip ()?

coord_flip.Rd. Flip cartesian coordinates so that horizontal becomes vertical, and vertical, horizontal. This is primarily useful for converting geoms and statistics which display y conditional on x, to x conditional on y.


2 Answers

coord_flip is a wrapper around coord_cartesian. You do two calls to coord_cartesian with the second overwriting the first. You can do this:

ggplot() +
  geom_pointrange(aes(x=myx, y=mean, ymin=lower, ymax=upper), data=the_data) +
  geom_pointrange(aes(x=myx, y=mean, ymin=lower, ymax=upper), data=the_data2) +
  coord_flip(ylim = c(-1, 1))
like image 86
Roland Avatar answered Oct 13 '22 00:10

Roland


It doesn't make sense to have multiple coordinate systems for the same plot. You want coord_flip(ylim = c(-1, 1))

like image 40
Ista Avatar answered Oct 13 '22 02:10

Ista