相对于变量的模态绘制具有不同颜色的 geom_vlines
Posted
技术标签:
【中文标题】相对于变量的模态绘制具有不同颜色的 geom_vlines【英文标题】:draw geom_vlines with different colors relative to the modalities of a variable 【发布时间】:2021-03-14 07:34:27 【问题描述】:我的绘图中有几个 geom_vline() 对应于变量“cas”更改值的日期,我希望它们相对于变量“cas”具有不同的颜色。有没有办法做到这一点?
这是我的代码:
df <- data.frame(date=c("2020-01-01 00:00:00","2020-01-01 03:00:00","2020-01-01 06:00:00","2020-01-01 09:00:00","2020-01-01 12:00:00","2020-01-01 15:00:00","2020-01-01 18:00:00",
"2020-01-01 21:00:00","2020-01-02 00:00:00","2020-01-02 03:00:00"), cas=c("cas 0", "cas 0", "cas 0", "cas 1", "cas 1", "cas 1", "cas 2", "cas 2", "cas 2", "cas 0"),
meteo=c("t", "t", "t_S1", "P_S1","t_S1","P_S1","t", "t_S1", "t_S1", "P_S1"), valeur = c(-2.364850,-2.274782,-2.229748,-2.034601,-1.704351,-1.644305,-1.584260,-1.554237,-1.479181,-1.509203))
date_cas <- df[which(df$cas != dplyr::lag(df$cas)),] %>% select(date) %>% unlist()
date_cas <- date_cas %>% lubridate::parse_date_time2(., "YmdHMS") %>% format(.,"%Y-%m-%d %H:%M:%S" )
ggplot(df, aes(x=lubridate::date(date), y =valeur,colour=meteo, group = meteo )) +
geom_line(size=0.8)+
geom_vline( aes ( xintercept = lubridate::date(df$date[which(df$date %in% date_cas), colour = df$cas[which((df$date) %in% date_cas)] ]) , size=1, linetype = "dashed")+
labs(y="", x = "Date")+
theme_minimal()
我收到此错误:
Erreur : Aesthetics must be either length 1 or the same as the data (10): xintercept and colour
有人可以帮忙吗?
【问题讨论】:
这能回答你的问题吗? plotting multiple geom-vline in a graph 感谢您的回复,但它并没有回答我的问题,事实上它在没有颜色的情况下可以正常工作,当我添加colour = df$cas[which((df$date) %in% date_cas)]
时出现错误
【参考方案1】:
我认为需要移动几个括号/方括号,并建议将geom_vline
中的df
子集化为data = df[df$date %in% date_cas, ]...
。这将有助于简化您的代码。看看这是否能满足您的需求。
library(lubridate)
library(ggplot2)
df$date <- lubridate::date(df$date)
ggplot(df, aes(x=date, y=valeur, colour=meteo, group=meteo)) +
geom_line(size=0.8)+
geom_vline(data = df[df$date %in% date_cas, ],
aes(xintercept=date, colour=cas),
size=1,
linetype = "dashed")+
labs(y="", x = "Date")+
theme_minimal()
【讨论】:
以上是关于相对于变量的模态绘制具有不同颜色的 geom_vlines的主要内容,如果未能解决你的问题,请参考以下文章