我尝试使用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帖子中所示。我试图从该帖子添加此代码:
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."
答案 0 :(得分:1)
在您放置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))