Variable hline in ggplot with facet

谁说我不能喝 提交于 2019-11-28 11:46:39

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!