21

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?

Roland
  • 127,288
  • 10
  • 191
  • 288
Alex
  • 1,997
  • 1
  • 15
  • 32

2 Answers2

31

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))
Roland
  • 127,288
  • 10
  • 191
  • 288
  • This makes sense. I figured it was something along these lines, just couldn't figure it out! Thanks! – Alex Oct 28 '15 at 14:56
6

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

Ista
  • 10,139
  • 2
  • 37
  • 38