I'm trying to use ggplot2 to create a timeline with annotated events. This is my data:
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))
This is the code that I'm using:
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))
What is produced currently looks fine but it doesn't have any annotated events, as found in this Stack Overflow post. I have tried to add this code from that 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)
but unsurprisingly, it isn't working (I assume because the arguments are conflicting, but I'm not sure how to resolve them).
As a note: The error it throws up when I try to use the full code above (with the hash lines un-hashed) is "Error: Discrete value supplied to continuous scale."
In your code for the annotation you put
x = Event
, when on your existing plot Date is on the x-axis, so you just need to make sure that both layers share the same x-axis scale: