R 如何使用ggplot以不同的颜色表示负值?
我想显示一个包含负值的数据框的绘图。在这种情况下,负值可用红线表示。但是我没有成功。当尝试绘制绘图时,由于cbind参数,负值开始按顺序排列。此外,我不知道如何组合数据帧R 如何使用ggplot以不同的颜色表示负值?,r,plot,ggplot2,shiny,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
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
set.seed(123)
tmp这是你想要的吗
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
库(ggplot2)
种子(1)
tmp我认为有几种方法可以让你接近你想要的
library(ggplot2)
set.seed(123)
tmp <- data.frame(time = 1:10, quantity = round(runif(10, -15, 25)) )
库(ggplot2)
种子集(123)
tmp您的代码给了我一个错误,您不明白吗?应该安装ggplot2包。@rawr是对的,您的代码有问题。首先,tmp1重新启动一个干净的r会话,然后只尝试你问题中的代码neg
不是data.frame
,而且它没有正确的“行数”,老实说,这不是我想要的。我不想看到另一行的负值。当tmp值低于零时,应改变线路颜色以“警告”或引起用户注意。
ggplot(tmp, aes(time, quantity, colour=(quantity <= 0))) +
geom_line(aes(group=1))
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")