通过x轴上的特定日期更改ggplot2-R中的颜色背景

我想基于特定日期(在X轴上)更改散点图中的背景颜色。 Ma的日期范围为2017年6月23日至2017年12月6日。我希望背景为6月23日至8月31日为绿色,其余为红色。

我在Change background color panel based on year in ggplot R处尝试过使用此脚本,但是它不起作用(老实说,我从未使用过ggplot2)。 日期变量是POSIXct格式。这是我使用的脚本,带有R给出的错误:

> ggplot() + geom_point() + 
geom_rect(aes(xmin = as.Date("2017-06-23"),xmax = as.Date("2017-08-31"),ymin = 0,ymax = Inf),fill="green",alpha = .2)+
geom_rect(aes(xmin = as.Date("2017-09-01"),xmax = as.Date("2017-12-06"),fill="red",alpha = .2)
Errore: Invalid input: time_trans works with objects of class POSIXct only

此脚本有什么问题(或遗漏了)?

如果有用的话,这是我的数据集str()的{​​{1}}

data

如果要尝试,这里有一些数据(数据集的前30行):

str(data)
'data.frame':   420 obs. of  2 variables:
 $ UTC.Date        : POSIXct,format: "2017-07-01" "2017-08-01" "2017-09-01" "2017-10-01" ...
 $ Mean.elevation  : num  1353 1098 905 747 1082 ...
john_anson 回答:通过x轴上的特定日期更改ggplot2-R中的颜色背景

您在geom_rect中输入的xmin,xmax必须与数据框中的类型相同,现在您在数据框中具有POSIXct,在geom_rect中具有Date。一种解决方案是,为geom_rect提供POSIX格式的数据:

# your data frame based on first 5 values
df = data.frame(
UTC.Date = as.POSIXct(c("2017-07-01","2017-08-01","2017-09-01","2017-10-01","2017-11-01")),Mean.elevation=c(1353,1098,905,747,1082))

RECT = data.frame(
       xmin=as.POSIXct(c("2017-06-23","2017-09-01")),xmax=as.POSIXct(c("2017-08-31","2017-12-06")),ymin=0,ymax=Inf,fill=c("green","red")
)

ggplot(df,aes(x=UTC.Date,y=Mean.elevation)) + geom_point()+
geom_rect(data=RECT,inherit.aes=FALSE,aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),fill=RECT$fill,alpha=0.2)

或将原始数据帧时间转换为日期:

df$UTC.Date = as.Date(df$UTC.Date)
ggplot(df,y=Mean.elevation)) + geom_point() + 
geom_rect(aes(xmin = as.Date("2017-06-23"),xmax = as.Date("2017-08-31"),ymin = 0,ymax = Inf),fill="green",alpha = .2)+
geom_rect(aes(xmin = as.Date("2017-09-01"),xmax = as.Date("2017-12-06"),fill="red",alpha = .2)

第一个解决方案给出如下内容:

enter image description here

,

我不认为需要在年份轴上放置颜色的零件有问题。下面的代码在我的系统上有效。

ggplot() + geom_point() + 
  geom_rect(aes(xmin = as.Date("2017-06-23"),alpha = .2)+
  geom_rect(aes(xmin = as.Date("2017-09-01"),alpha = .2)

我认为绘制实际数据会出错(您提供的代码中未包含该数据)。 您可以检查this question上的答案是否对您有所帮助?

本文链接:https://www.f2er.com/3082321.html

大家都在问