简体   繁体   中英

how to use coord_carteisan and coord_flip together in 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?

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM