I am creating a lexis plot for a dataframe with ages 0:80, for years 1900:2020, and values 0:20. I want to use geom_abline to create diagonal lines through the lower left and upper right corners of the boxes created by vertical and horizontal lines at increments of 10. However, the abline is not showing up. Dummy data below:
df <- data.frame(age = as.numeric(),
year = as.numeric(),
value = as.numeric())
for(x in c(1900:2020)){
temp <- data.frame(age = c(0:80),
year = x,
value = sample(0:20, 81, TRUE))
df <- rbind(df, temp)
}
myplot <- ggplot(df, aes(x=year, y=age, fill=value)) +
geom_tile() +
scale_fill_viridis(labels = scales::label_comma(), direction = -1) +
geom_hline(yintercept=seq(0, 80, by=10), size = 0.5) +
geom_vline(xintercept=seq(1900,2030, by=10), size = 0.5) +
geom_abline(intercept=seq(-80,80, by = 10), slope = 1, size = 0.5) +
xlab("Year") +
ylab("Age") +
coord_fixed() +
theme(plot.subtitle = element_text(size = 10, face = "italic"))
myplot
>Solution :
You have to account for the range of your x scale, i.e. use intercept = seq(-80, 80, by = 10) - 1900:
library(ggplot2)
library(viridis)
ggplot(df, aes(x = year, y = age, fill = value)) +
geom_tile() +
scale_fill_viridis(labels = scales::label_comma(), direction = -1) +
geom_hline(yintercept = seq(0, 80, by = 10), linewidth = 0.5) +
geom_vline(xintercept = seq(1900, 2030, by = 10), linewidth = 0.5) +
geom_abline(intercept = seq(-80, 80, by = 10) - 1900, slope = 1, linewidth = .5, color = "red") +
xlab("Year") +
ylab("Age") +
coord_fixed() +
theme(plot.subtitle = element_text(size = 10, face = "italic"))

