2017-05-04 53 views
4

假设我有这样的情节:更改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) 

Output picture

我怎样才能改变绘图命令,使红线 被其它两个以上绘制?

因此,背景是我有非常相似的 线的图,并且希望在前景中看到特定的线。

我想根据这个答案order of stacked bars in ggplot会行。它使颜色列的因素,并改变他们的顺序,但我宁愿改变 这直接在ggplot调用的一行。

我也尝试用scale_color_discrete(breaks=c("r", "g", "b"))), 更改图例顺序,但这并不影响绘图顺序。

回答

5

所以实际上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")) 

enter image description here

+0

找了份有点困惑,因为我们的例子中有不同的颜色,但现在很好用!我想我必须将因素合并到我的ggplot例程中。 – Simon

+1

对不起,只是红'r'' g'和'b',并认为这符合颜色。将相应地编辑我的答案。 – thothal

+0

再次感谢,现在也适用于我的应用示例。在第一次混淆之前澄清我的意思:虽然这种方法确实起作用,但它看起来好像只改变了红色和蓝色线之间的颜色,因为同一条线在我们的两幅图上位于最前面。 (我不应该给我的线路名称r,b,g,它们与自动颜色不匹配。) – Simon

1
library(ggplot2) 
df <- 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() + 
    geom_line(data = df[3:4,], aes(x = x, y = y), color = 'blue', size = 3) + 
    geom_line(data = df[5:6,], aes(x = x, y = y), color = 'green', size = 3) + 
    geom_line(data = df[1:2,], aes(x = x, y = y), color = 'red', size = 3) 
+0

在我看来,作为一种备份是很好的,我也有时会使用这种备份。但它不能用自动ggplot的方式工作,特别是如果你的数据帧是长格式的。 – Simon