[英]ggplot2 place rect or tile based on factor in time series R
我有一個線圖,我想根據某列是否為1來在背景中覆蓋一個矩形或彩色帶。
這是一個例子:
df <- data.frame(date = seq.Date(as.Date("2015-01-01"), as.Date("2016-12-01"), by = "month"),
value = c(rep(NA, 5), rep(1, 2), rep(NA, 3), rep(1, 10), rep(NA, 4)))
df2 <- data.frame(date = seq.Date(as.Date("2015-01-01"), as.Date("2016-12-01"), by = "month"),
values = c(rep(1, 10), rep(2, 10), rep(3, 4)))
我嘗試過的
ggplot(df2, aes(x = date, y = values)) +
geom_line() +
geom_tile(data = df, aes(fill = "value"), inherit.aes = FALSE)
Error in eval(substitute(list(...)), `_data`, parent.frame()) :
object 'x' not found
In addition: Warning messages:
1: In min(x, na.rm = na.rm) :
no non-missing arguments to min; returning Inf
2: In max(x, na.rm = na.rm) :
我只想df$value
線圖,然后在df$value
為1
地方將背景塗成灰色。
從梅利莎(Melissa)的解決方案中,我很接近,但出現了怪異的話:
您將需要進行一些操作,但這將為您帶來大部分所需的功能:
df3 <- left_join(df2, df)
ggplot(df3, aes(x = date, y = values)) +
geom_line() +
geom_tile(aes(x = date, fill = !is.na(value)), width = 30, height = .4, alpha = 0.5, color = NA) +
scale_fill_manual(values = c("gray20", NA))
或讓背景延伸到y軸的整個范圍:
ggplot(df3, aes(x = date, y = values)) +
geom_line() +
geom_tile(aes(x = date, fill = !is.na(value)), width = 30, height = Inf, alpha = 0.5) +
scale_fill_manual(values = c("gray20", NA))
此時的寬度還不太合適-您可以嘗試切換到geom_rect
來通過左右兩點而不是中間點來定義寬度(請參閱geom_rect
或geom_tile
的說明以弄清楚部分。
這是geom_rect
的答案,這是此應用程序的另一選擇。 ggplot
非常ggplot
在geom
規范中對數據進行子集設置,因此類似這樣的方法可能適用於您的情況:
df <- data.frame(date = seq.Date(as.Date("2015-01-01"), as.Date("2016-12-01"), by = "month"),
value = c(rep(1, 6), rep(NA, 4), rep(1, 10), rep(NA, 4)))
df2 <- data.frame(date = seq.Date(as.Date("2015-01-01"), as.Date("2016-12-01"), by = "month"),
values = c(rep(1, 10), rep(2, 10), rep(3, 4)))
library(ggplot2)
library(lubridate)
ggplot() +
geom_rect(data=subset(df,value==1), aes(xmin=date, xmax=date+months(1), ymin=-Inf, ymax=Inf), fill="light grey", colour=NA) +
geom_line(data=df2, aes(x = date, y = values)) +
theme_classic()
這種方法還分別維護df
和df2
,但是我同意最好將它們加入,因為每個日期都有相同的日期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.