[英]How can I indicate negative values in different colour in shiny with ggplot?
I would like to display plot of a data frame which includes negative values either.我想显示一个包含负值的数据框的图。 In this case, the negative values may be indicated with red line.
在这种情况下,负值可以用红线表示。 However I couldn't succeed.
然而我没能成功。 When try to draw the plot, the negatives values began to follow sequence because of cbind argument.
尝试绘制绘图时,由于 cbind 参数,负值开始遵循顺序。 In addition, I don't know another way to combine the data frames.
另外,我不知道另一种组合数据框的方法。
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
A couple of methods I think get you close to what you're after.我认为有几种方法可以让您接近您所追求的目标。
library(ggplot2)
set.seed(123)
tmp <- data.frame(time = 1:10, quantity = round(runif(10, -15, 25)) )
method 1 - colour line by expression方法 1 - 按表达式着色线条
This will colour the line from the point the quantity is negative, until the time the quantity is non-negative again.这将从数量为负的点开始为线条着色,直到数量再次为非负的时间。
ggplot(tmp, aes(time, quantity, colour=(quantity <= 0))) +
geom_line(aes(group=1))
Method 2 - adding an extra column to so we can colour two lines, one is the complete 'quantity' column, and the other is only those values that are negative, or either size of a negative.方法 2 - 添加一个额外的列,以便我们可以为两行着色,一个是完整的“数量”列,另一个是负值或负值的任一大小。 (otherwise they'll be NA)
(否则他们将成为 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")
If you want it to only change colour when the line crosses the x==0
line you may have to manipulate the data a bit more如果您希望它仅在线穿过
x==0
线时改变颜色,您可能需要更多地操作数据
Does this do what you want?这是你想要的吗?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.