本文介绍了更改ggplot中线的覆盖顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这个情节:
library(ggplot2)
pl_data <- data.frame(x = rep(c(1, 2), times = 3), y = c(0, 1, 1, 0, .7, .7), col = rep(c("r", "b", "g"), each = 2))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
geom_line(size = 3)
如何更改打印顺序,以便红线排在其他两个上方?
How can I change the plotting order, so that the red lineis plotted above the other two?
因此,背景是我的情节非常相似行,并希望在前景中看到特定的行.
The background therefore is that I have plots with very similarlines, and want to see specific lines in the foreground.
我猜想与此答案类似的内容 ggplot中堆积条形的顺序会工作.它使颜色列受因素影响并更改其顺序,但我希望更改这直接在ggplot调用的一行中.
我还尝试使用scale_color_discrete(breaks=c("r", "g", "b"))
更改图例顺序,但这也不影响打印顺序.
推荐答案
因此,实际上col
的最后一层位于顶部.因此,您需要更改因子的顺序并反转颜色,因为红色会自动映射到第一级(使用标准颜色来说明问题):
pl_data$col <- factor(pl_data$col, c("r", "g", "b"))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
geom_line(size = 3) +
scale_color_manual(values = c(r = "blue", g = "green", b = "red"))
## with standard colors of ggplot2, function taken from:
## http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
ggplotColours <- function(n = 6, h = c(0, 360) + 15) {
if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}
pal <- setNames(ggplotColours(3), c("b", "g", "r"))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
geom_line(size = 3) +
scale_color_manual(values = pal, breaks = c("b", "g", "r"))
这篇关于更改ggplot中线的覆盖顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!