首页 > 解决方案 > 如何在现有地块上叠加一个框?

问题描述

我试图在特定的 x = 日期和 y = 价格的图上绘制一个框。

我有多个 Date 条目存储在 specificDates 中,但即使代码可以运行并且不输出任何错误,该框也不会显示在图上。

dataDate <- as.Date(c("2015-01-01","2016-03-01","2018-06-01","2020-08-01"))
dataPrice <- c(170, 320, 7000,8000)
dummyData <- data.frame(dataDate, dataPrice)
specificDates <- as.Date(c("2016-07-15", "2020-05-20"))

plot_linPrice <- ggplot(data = dummyData,
                        mapping = aes(x = dataDate, y = dataPrice)) +
  geom_line() +
  scale_y_log10() +
  geom_vline(xintercept = as.numeric(specificDates), color = "blue", lwd = .5) #+  #uncommenting + brings up error
  geom_rect(aes(xmin = "2015-01-01", xmax = "2015-06-01", ymin = 5000, ymax = 8000), fill = "blue")

print(plot_linPrice)

标签: rggplot2plot

解决方案


试试这个:

library(ggplot2)
#Data
dataDate <- as.Date(c("2015-01-01","2016-03-01","2018-06-01","2020-08-01"))
dataPrice <- c(170, 320, 7000,8000)
dummyData <- data.frame(dataDate, dataPrice)
specificDates <- as.Date(c("2016-07-15", "2020-05-20"))
#Code
ggplot(data = dummyData,
                        mapping = aes(x = dataDate, y = dataPrice)) +
  geom_line() +
  scale_y_log10() +
  geom_vline(xintercept = as.numeric(specificDates), color = "blue", lwd = .5)+
  geom_rect(aes(xmin = as.Date("2015-01-01"), xmax = as.Date("2015-06-01"), ymin = 5000, ymax = 8000), fill = "blue")

输出:

在此处输入图像描述


推荐阅读