Variable hline in ggplot with facet

后端 未结 1 2012
一生所求
一生所求 2020-12-10 20:55

Using the Iris data set as an example, I can produce a ggplot with facet. The code is:

library(ggplot2)
data(iris)
y=iris
y$Petal.Width.Range=factor(ifelse(         


        
相关标签:
1条回答
  • 2020-12-10 21:38

    One easy solution is just to change your hline call to this: geom_hline(aes(yintercept=threshold), alpha=0.3) +.

    The problem is, that would draw 150 lines on your plot (150 being the number of rows in the y data.frame). Maybe that's ok with you, because the lines would mostly be stacked on top of each other and you would really only see four lines, in their correct locations.

    However, here is another solution where I create a smaller auxiliary data.frame. This is a common approach in ggplot2. Notice how the new data.frame is specified as the data source inside the geom_hline call.

    hline_dat = data.frame(Petal.Width.Range=c("Narrow", "Narrow", "Wide", "Wide"),
                           Petal.Length.Range=c("Short", "Long", "Short", "Long"),
                           threshold=c(2, 2.5, 3.1, 4))
    
    p = ggplot(y, aes(Sepal.Length,Sepal.Width)) + 
        geom_point(alpha=0.5) +
        geom_hline(data=hline_dat, aes(yintercept=threshold), colour="salmon") +
        facet_grid(Petal.Width.Range ~ Petal.Length.Range)
    
    ggsave("plot.png", plot=p, height=4, width=6)
    

    0 讨论(0)
提交回复
热议问题