在 ggplot2 中绘制带有指定时间段和注释事件的时间线

Drawing a timeline with denoted time periods AND annotated events in ggplot2

我正在尝试使用 ggplot2 创建带有注释事件的时间线。这是我的数据:

cambodia = data.frame(Period = c("Funan", "Chenla/Zhenla","Khmer Empire","Dark Ages of Cambodia"),StartDate = c(-500,550,802,1431), EndDate = c(550,802,1431,1863))

cambodia.events = data.frame(Event = c("Migration of peoples from southeastern China\ninto Cambodia"), Date=c(50), disloc = c(1))

这是我正在使用的代码:

library(ggplot2)
library(viridis)
library(ggthemes)

ggplot(data=cambodia) +
  geom_segment(aes(x=StartDate, xend=EndDate, y=0., yend=0., color=Period) , linetype=1, size=4) +
  scale_color_viridis(discrete = TRUE)+
  scale_y_continuous(limits=c(0,0.5))+
  scale_x_continuous(limits=c(-500,1863),  breaks= c(seq(0,1863,by=1863), cambodia$StartDate, cambodia$EndDate))+
  xlab("Time")+
  ylab("Periods of History")+
  theme_minimal() + theme(panel.grid.minor = element_blank(), panel.grid.major =   element_blank(), axis.title.y=element_blank(),axis.text.y=element_blank(),  axis.ticks.y=element_blank()) +
  theme(aspect.ratio = .2)+
  theme(legend.position="none") + 
  geom_text(aes(x=StartDate-100 + (EndDate- StartDate)/2,y=0.05,label=Period,angle=25,hjust=0)) 

当前生成的内容看起来不错,但它没有任何带注释的事件,如 this Stack Overflow post 中所见。我试图从 post:

添加这段代码
 geom_segment(aes(x = Event,y = disloc,xend = Event),data=cambodia.events,yend = 0) +
  geom_segment(aes(x = 900,y = 0,xend = 2050,yend = 0),data=cambodia.events,arrow = arrow(length = unit(x = 0.2,units = 'cm'),type = 'closed')) +
  geom_text(aes(x = Event,y = disloc,label = Date),data=cambodia.events,hjust = 1.0,vjust = 1.0,parse = FALSE) 

但不出所料,它不起作用(我假设是因为参数相互冲突,但我不确定如何解决它们)。

注意:当我尝试使用上面的完整代码(散列行未散列)时抛出的错误是 "Error: Discrete value supplied to continuous scale."

在您放置 x = Event 的注释代码中,当您现有绘图上的日期位于 x 轴上时,您只需确保两个图层共享相同的 x 轴刻度:

ggplot() +
  geom_segment(data = cambodia, aes(x = StartDate, xend = EndDate, y = 0, yend = 0, color = Period), linetype = 1, size = 4) +
  geom_text(data=cambodia, aes(x=StartDate-100 + (EndDate- StartDate)/2,y=0.05,label=Period,angle=25,hjust=0)) +
  scale_color_viridis(discrete = TRUE)+
  scale_y_continuous(limits=c(0, 0.5))+
  scale_x_continuous(limits=c(-500, 1863), breaks= c(seq(0, 1863, by = 1863), cambodia$StartDate, cambodia$EndDate))+
  xlab("Time")+
  ylab("Periods of History")+
  theme_minimal() + 
  theme(panel.grid.minor = element_blank(), 
      panel.grid.major = element_blank(), 
      axis.title.y = element_blank(), 
      axis.text.y=element_blank(),  
      axis.ticks.y=element_blank(),
      aspect.ratio = .2,
      legend.position="none") +
geom_segment(data = cambodia.events, aes(x = Date, xend = Date, y = 0, yend = .25)) +
geom_text(data = cambodia.events, aes(x = Date, y = .35, label = Event))