当值低于零时如何使线为红色,高于时为绿色?
我希望当图表上的线低于 0 时为红色且高于绿色。我试图弄清楚我自己,但是,当我只需要低于 y=0 的颜色时,该代码在周五至周六的整个部分为我提供了一种颜色(“红色”,因为它低于 0)。
a<-structure(list(group = c("Total", "Total", "Total", "Total",
"Total", "Total", "Total"), measure = c("sales", "sales", "sales",
"sales", "sales", "sales", "sales"), day = structure(1:7, .Label = c("MONDAY",
"TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"
), class = "factor"), variable = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("ALL", "DE", "BE", "NL", "AUS", "ES",
"IT", "FR", "PO"), class = "factor"), value = c(2400000, 3750000,
3400000, 3100000, 2300000, 3600000, 3100000), per_mtoday = c(2400000,
2400000, 2400000, 2400000, 2400000, 2400000, 2400000), per_mtoday_perc = c(0,
0.5625, 0.416666666666667, 0.291666666666667, -0.0416666666666667,
0.5, 0.291666666666667), colour1 = c("green", "green", "green",
"green", "red", "green", "green")), row.names = c(1L, 15L, 29L,
43L, 57L, 71L, 85L), class = "data.frame")
ggplot(a, aes(x=day, y=per_mtoday_perc,fill = colour1, color= colour1,group = 1)) +
geom_line(lwd=1.5)+
scale_y_continuous(labels = scales::percent)
回答
正如康拉德·鲁道夫 (Konrad Rudolph) 所建议的那样,此处正确的做法是对这些值进行插值以找到 y 轴上的零交叉点。由于正确执行这可能有点费力,因此这里有一种使用ggforce::geom_link2(). 该函数已经通过图层的 stat 部分在点的 xy 坐标之间进行插值,因此我们可以使用该after_stat()函数根据插值点的 y 值进行着色。
library(ggplot2)
library(ggforce)
ggplot(a, aes(x=day, y=per_mtoday_perc,fill = colour1, color= colour1,group = 1)) +
geom_link2(lwd=1.5,
aes(colour = after_stat(y < 0)))+
scale_colour_manual(
values = c("limegreen", "red")
) +
scale_y_continuous(labels = scales::percent)