在ggplot中显示一个矩形,x轴为日期格式

时间:2017-10-18 07:21:04

标签: r date ggplot2

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

我知道这段代码:

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

但是如果x轴是日期格式怎么办? xmin xmax 的语法是什么?像"2008-05-03 UTC"这样的东西似乎不起作用。

1 个答案:

答案 0 :(得分:3)

+-----------+-------+--------------------+-------------+-----------------+-------------+-----------+
| AmountDue | ASMID | ASM_Descr          | PMT_Descr   | PaymentsApplied | PaymentList | PMT_ASMID |
+-----------+-------+--------------------+-------------+-----------------+-------------+-----------+
|      NULL |  NULL | NULL               | Deposit Fee |        600.0000 | 4           |         0 |
|      NULL |  NULL | NULL               | Rent Fee    |       1100.0000 | 1,2         |         1 |
|      NULL |  NULL | NULL               | Damage Fee  |         20.0000 | 3           |         2 |
| 1200.0000 |     1 | Rent               | NULL        |            NULL | NULL        |      NULL |
|   20.0000 |     2 | Damage - car break | NULL        |            NULL | NULL        |      NULL |
|  500.0000 |     3 | Damage - vehicle   | NULL        |            NULL | NULL        |      NULL |
+-----------+-------+--------------------+-------------+-----------------+-------------+-----------+

enter image description here

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) 也会起作用,但你需要欺骗代码才能表现出alpha,例如。

geom_rect