R中的scale_x_discrete之后geom_vline不起作用

我是新手,很抱歉没有正确填写问题:p

1,目的是绘制一个有关我的研究站点(名为RB1)的时间段(从2019-05到2019-10的8个日期,共8个日期)中平均NDVI值的图表。并绘制垂直线以显示割草事件的日期。

2,现在我已经计算出这8个选定日期的NDVI值,并制作了一个CSV文件。 (PS。“切割”是指研究地点的草地已被切割,因此应使用geom_vline将相应的日期显示为垂直线)

infor <- read_csv("plotting information.csv")
infor
# A tibble: 142 x 3
   date         NDVI cutting
   <date>      <dbl> <lgl>  
 1 2019-05-12 NA     NA     
 2 2019-05-13 NA     NA     
 3 2019-05-14 NA     NA     
 4 2019-05-15 NA     NA     
 5 2019-05-16 NA     NA     
 6 2019-05-17  0.787 TRUE      
# ... with 132 more rows

3,问题是,当我执行ggplot时,首先我想将x轴保留为整个时间段(2019-05至2019-10),但是当然不显示其间的所有日期,否则x轴上会显示太多日期)。因此,我执行scale_x_discrte(breaks=,labels=)以显示具有NDVI值的特定日期。

第二,我还想显示割草geom_vline的日期。

但是,看来scale_x_discrte的前提是factor我的日期,而geom_vline的前提是将日期保持为nummeric。  这两个电话似乎是矛盾的。

y1 <- ggplot(infor,aes(factor(date),NDVI,group = 1)) +
  geom_point() +
  geom_line(data=infor[!is.na(infor$NDVI),]) + 
  scale_x_discrete(breaks = c("2019-05-17","2019-06-18","2019-06-26","2019-06-28","2019-07-23","2019-07-28","2019-08-27","2019-08-30","2019-09-21"),labels = c("0517","0618","0626","0628","0723","0728","0827","0830","0921"))) 


y2 <- ggplot(infor,aes(date,])) 

当我在y1中添加geom_vline时,我的绘图上不显示垂直线: y1 + geom_vline

当我将其添加到y2中时,显示了垂直线,但是日期(x轴)很奇怪(不显示为y1,因为我们不在此处运行scale_x_)  y2 + geom_vline

   y1 + 
      geom_vline(data=filter(infor,cutting == "TRUE"),aes(xintercept = as.numeric(date)),color = "red",linetype ="dashed")

如果能提供帮助,将不胜感激! 提前致谢! :D

diano1991 回答:R中的scale_x_discrete之后geom_vline不起作用

我同意有关将日期保留为日期的评论。在这种情况下,您可以将geom_vline的x截距指定为日期。

给出基本数据:

df <- tribble(
  ~Date,~Volume,~Cut,'1-1-2010',123456,'FALSE','5-1-2010',789012,'TRUE','9-1-2010',5858585,'12-31-2010',2543425,'FALSE'
)

我设置了日期,然后将Cut=='TRUE'的子集放入一个新对象:

df <- mutate(df,Date = lubridate::mdy(Date))

d2 <- filter(df,Cut == 'TRUE') %>% pull(Date)

最后使用该对象指定拦截:

df %>%
  ggplot(aes(x = Date,y = Volume)) +
  geom_vline(xintercept = d2) +
  geom_line()
本文链接:https://www.f2er.com/3071957.html

大家都在问