2016-10-14 52 views
1

我有一个facet_grid,并且希望根据增长变量的符号为不同线条上的点着色。出于某种原因,我在大多数面板中都会看到2行。正如您从图表中看到的,它无法正常工作。ggplot facet_grid用标记的颜色

df2$sign <- paste(sign(df2[df2$variable %in% c('growth'), 'value'])) 
gg <- ggplot(df2, aes(x = date, y = value, colour = sign)) + geom_line() + facet_grid(variable ~ ., scales = 'free_y') 
gg <- gg + scale_fill_manual(values = c('1' = "green", '-1' = "red", 'NA' = 'black')) 

enter image description here

更新,整个dput可能是太多,这里是一大块

> dput(df2[sort(sample(1:nrow(df2), 20)), ]) 
structure(list(date = structure(c(113, 204, 330, 442, 764, 834, 
274, 582, 239, 316, 533, 57, 680, 715, 813, 120, 162, 260, 582, 
785), class = "Date"), variable = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L 
), .Label = c("x", "trline", "abovtrend", "growth", "growthpc" 
), class = "factor"), value = c(13.3161181999425, 16.1064371699508, 
17.4335499999019, 15.7080705228661, 21.2452347312702, 24.1828936950835, 
15.8272720823308, 19.1001953187372, 0.716627289232031, 0.618404918297323, 
-0.219587860370801, NA, 4.20745119442357, 1.15183152074574, 0.978670728352593, 
NA, NA, NA, 0.808835828791911, 0.179073426736106), sign = c("NA", 
"NA", "NA", "-1", "1", "1", "NA", "1", "NA", "NA", "1", "NA", 
"1", "1", "1", "NA", "NA", "NA", "1", "1")), .Names = c("date", 
"variable", "value", "sign"), row.names = c(17L, 30L, 48L, 64L, 
110L, 120L, 160L, 204L, 275L, 286L, 317L, 369L, 458L, 463L, 477L, 
498L, 504L, 518L, 564L, 593L), class = "data.frame") 
+2

我们_kinda_需要df2代表样本的输出或代表性的模拟数据。 – hrbrmstr

+0

可能的罪魁祸首是你只使用'geom_line()'。我会建议添加'geom_point()'并仅着色。无需以不同的方式对整条线着色。 –

+0

感谢您发布数据 - 只是为了让您知道它只有'variable =“x”',所以这一切都不会做任何事情。 –

回答

0

像@hrbrmstr在他的评论中说,我们真正需要的数据在这里给一个明确的答案,但我相信你会得到你所得到的结果,因为你实际上没有给你的情节加点颜色。你给你的线涂上颜色。这是你想要的吗?

df <- data.frame(
    x = 1:5, 
    y1 = c(1, 2, -2, -3, 5) 

) 
df$color <- ifelse(is.na(df$y1), "NA",ifelse(df$y1 < 0,"-1","1")) 
ggplot(df, aes(x, y1)) + geom_point(aes(color=color),size=4) + geom_line() + theme_minimal() 

这个颜色指向0以下,红色以及蓝色以上。改变颜色也很容易。

enter image description here

0

如果您希望能够以色行,不破坏它们,你需要告诉ggplot将它们视为一组,用group像这样(使用@ MikeyMike对简单数据):

ggplot(df, aes(x, y1, color = color, group = 1)) + 
    geom_point() + 
    geom_line() 

enter image description here

否则,它假定色组应分别绘制。明确设置group将覆盖它。您可能需要更改计算符号的方式,以确保您想要的线段是有颜色的,但这应该给您一个良好的开始。