首页 > 解决方案 > 更改 ggplot2 中的颜色背景 - R 按 x 轴上的特定日期

问题描述

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

我已经在此处尝试使用此脚本更改背景颜色面板,基于 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"),ymin = 0, ymax = Inf),
          fill="red", 
          alpha = .2)
Errore: Invalid input: time_trans works with objects of class POSIXct only

这个脚本有什么问题(或遗漏)?

如果它有用,这是str()我的数据集data

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 ...

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

UTC.Date           Mean.elevation
1  2017-07-01      452.88224
2  2017-08-01      499.03211
3  2017-09-01      600.52692
4  2017-10-01      554.38923
5  2017-11-01      424.03798
6  2017-07-02      697.89243
7  2017-08-02      404.75938
8  2017-09-02      104.60064
9  2017-10-02     2194.45778
10 2017-11-02      314.21575
11 2017-12-02      464.44365
12 2017-07-03      876.20422
13 2017-08-03      308.53507
14 2017-09-03      377.45005
15 2017-10-03      805.73900
16 2017-11-03      405.05043
17 2017-07-04      939.72697
18 2017-08-04      508.95055
19 2017-09-04      763.68243
20 2017-10-04       64.56294
21 2017-11-04      783.69125
22 2017-07-05      505.33392
23 2017-08-05     1164.36239
24 2017-09-05     1534.99598
25 2017-10-05       12.05559
26 2017-11-05     1209.14527
27 2017-07-06      167.01947
28 2017-08-06      451.23450
29 2017-09-06      989.66036
30 2017-10-06       54.97960

标签: rggplot2

解决方案


您在 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,aes(x=UTC.Date,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"),ymin = 0, ymax = Inf),
          fill="red", 
          alpha = .2)

第一个解决方案给出了类似的东西:

在此处输入图像描述


推荐阅读