简体   繁体   中英

Ordering of ggplot2 facets changes after adding to a facet

I changed the levels of the factor to desired ordering before using the ggplot2 's facet_wrap . It works fine as in the first example.

In the second, I added a horizontal like to one of the facets. It has changed the ordering of the facets.

How do I stop this automatic change?

mpg2 <- mpg
mpg2$drv <- factor(mpg2$drv, levels = c("r", "4", "f"))

p <- ggplot(mpg2, aes(cty, hwy)) + 
  geom_point() + 
  facet_grid(rows = vars(drv), scales = "free")
p

在此处输入图像描述

p + geom_hline(data = data.frame(xint = 20, drv = "r"),
          aes(yintercept = xint), linetype = "dotted", color = "blue") 

在此处输入图像描述

The dataframe for the line, column drv must have same factor levels as original dataframe mpg2:

p + geom_hline(data = data.frame(xint = 20, 
                                 drv = factor("r", levels = levels(mpg2$drv))),
               aes(yintercept = xint), linetype = "dotted", color = "blue")

在此处输入图像描述

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