Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

abline not showing in ggplot

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

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"))

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading