本文介绍了在ggplot中以x轴显示日期格式的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I display a rectangle in ggplot with x axis in date format?

我知道此代码:

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

但是,如果x轴为日期格式怎么办? xmin xmax 的语法是什么?像 2008-05-03 UTC 之类的方法似乎无效。

But what if the x axis is in date format? What's the syntax for xmin and xmax? something like "2008-05-03 UTC" doesn't seem to work.

推荐答案

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起作用,例如

geom_rect would work too, but you would need to trick the code for alpha to behave, e.g.

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)

这篇关于在ggplot中以x轴显示日期格式的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 22:38