簡體   English   中英

在ggplot中顯示一個矩形,x軸為日期格式

[英]Display a rectangle in ggplot with x axis in date format

如何在ggplot中以x軸顯示日期格式的矩形?

我知道這段代碼:

geom_rect(xmin = 0, xmax = 1, ymin = 0, ymax = 1,   fill = "blue")

但是如果x軸是日期格式怎么辦? xminxmax的語法是什么? "2008-05-03 UTC"這樣的東西似乎不起作用。

set.seed(4)
df <- data.frame(date=as.Date(paste0("2017-01-", sprintf("%02d", 1:31))),
             val= sample(1:100, 31))

p <- ggplot(df, aes(date, val)) + geom_point()

p + annotate("rect",
    xmin = as.Date("2017-01-15"), xmax = as.Date("2017-01-20"), 
    ymin = -Inf, ymax = Inf,  fill = "blue", alpha=.3)

在此輸入圖像描述

geom_rect也可以工作,但你需要欺騙代碼才能表現出alpha,例如

p + geom_rect(data=df[1,], 
             aes(xmin = as.Date("2017-01-15"), xmax = as.Date("2017-01-20"),
             ymin = -Inf, ymax = Inf),  
             fill = "blue", alpha=.3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM