当值小于零时如何使线变为红色,而值大于零时如何使线变为绿色? [英] How make line red when the value is below zero and green when above?

查看:39
本文介绍了当值小于零时如何使线变为红色,而值大于零时如何使线变为绿色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望当图表上的线低于0时,该线为红色,而在绿色上方.我试图弄清楚自己的身份,但是,当我只需要在y = 0以下时,该代码为我提供了周五至周六整个时间的颜色(红色",因为它低于0).

I want that when the line is below 0 on the graph to be red and above green. I tried to figure out my self, however, the code gives me a color ("red" as it is below 0) for the whole part of Friday-Saturday when I need this colour only below y=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-part在点的xy坐标之间进行插值,因此我们可以使用 after_stat()函数根据插值点的y值进行着色.

The correct thing to do here would be, as Konrad Rudolph suggested, to interpolate the values to find the zero-crossing points on the y axis. Since that can be a little bit laborious to do properly, here is a quick way to approximate this using ggforce::geom_link2(). The function already interpolates between the xy-coordinates of points through the stat-part of the layer, so we can colour depending on the y-values of the interpolated points using the after_stat() function.

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)

这篇关于当值小于零时如何使线变为红色,而值大于零时如何使线变为绿色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆