如何用ggplot指示闪亮的不同颜色的负值?

时间:2016-01-17 21:54:07

标签: r plot ggplot2 shiny

我想显示包含负值的数据框图。在这种情况下,负值可以用红线表示。但是我无法成功。当尝试绘制图时,由于cbind参数,负值开始遵循序列。另外,我不知道另一种组合数据帧的方法。

set.seed(123)
tmp <- data.frame(time = 1:10, quantity = round(runif(10, -15, 25)) )

neg <- tmp$quantity[tmp$quantity <0]
tmp.pred <-  cbind(tmp,neg)

y <- ggplot(tmp, aes(time, quantity)) + 
 geom_line() +   
 geom_line(data=tmp.pred, aes(y=neg),color="red") 
 y

enter image description here

2 个答案:

答案 0 :(得分:2)

我认为有两种方法让你接近你所追求的目标。

library(ggplot2)

set.seed(123)
tmp <- data.frame(time = 1:10, quantity = round(runif(10, -15, 25)) )

方法1 - 按表达式划分颜色

这将从数量为负的点开始着色,直到数量再次为非负数。

ggplot(tmp, aes(time, quantity, colour=(quantity <= 0))) + 
geom_line(aes(group=1))

enter image description here

方法2 - 添加一个额外的列,以便我们可以为两条线着色,一条是完整的“数量”列,另一条只是那些负数的值,或者是一个大小的负。 (否则他们将是NA)

library(dplyr)
tmp <- tmp %>%
    mutate(neg = ifelse(quantity <= 0, quantity, NA)) %>%
    mutate(neg = ifelse(is.na(neg) & lag(neg) <= 0, quantity, neg)) %>%
    mutate(neg = ifelse(is.na(neg) & lead(neg) <= 0, quantity, neg))

ggplot() +
    geom_line(data=tmp, aes(x=time, y=quantity) , colour="black") +
    geom_line(data=tmp, aes(x=time, y=neg), colour="red")

enter image description here

如果您希望它仅在线穿过x==0线时更改颜色,则可能需要更多地操作数据

答案 1 :(得分:0)

这样做你想要的吗?

library(ggplot2)
set.seed(1)
tmp <- data.frame(time = 1:10, quantity = round(runif(10, -15, 25)) )
tmp$series <- ifelse(tmp$quantity < 0, "Negative", "Positive")
y <- ggplot(tmp, aes(x = time, y = quantity, colour = series)) + 
  geom_line() +
  scale_colour_manual(values=c("red", "blue"))
y