Home > Back-end >  How to build slope plots in R?
How to build slope plots in R?

Time:05-13

I have dataframe which represents sales by model within 2 different years. 'change' column stands for absolute change by models from 2020 to 2021 while 'chng.percent' measures this change in percentages.

df <- data.frame (model  = c("A", "A", "B","B"),
                  year = c(2020,2021,2020,2021),
                  sale =c(105,190,110,180),
                  chang = c(85,NA,70,NA),
                  chng.percent = c(80.9,NA, 63.6,NA))

Now I am struggling to build slope plots in R: (enter image description here I want to build slope lot add changes in absolute and percentages lines colours according to model categorical variable

Expected output: enter image description here

CodePudding user response:

What about this:

library(tidyverse)
df <- data.frame (model  = c("A", "A", "B","B"),
                   year = c(2020,2021,2020,2021),
                   sale =c(105,190,110,180),
                   chang = c(85,NA,70,NA),
                   chng.percent = c(80.9,NA, 63.6,NA)) 

labs <- df %>% 
  group_by(model) %>% 
  slice_head(n=1)


ggplot(df, aes(x=year, y=sale, colour = model))   
  geom_line(show.legend = FALSE)   
  geom_point()  
  geom_text(data = subset(df, year==2020), aes(x=year, y=sale, label=sale), hjust=1, nudge_x = -.05, show.legend = FALSE, inherit.aes = FALSE)   
  geom_text(data = subset(df, year==2021), aes(x=year, y=sale, label=sale), hjust=0, nudge_x = .05, show.legend = FALSE, inherit.aes = FALSE)   
  geom_text(aes(x=2020.75, y=140, label = sprintf(" %.1f, %.1f%%", labs$chang[2], labs$chng.percent[2]), colour=labs$model[2]), show.legend = FALSE)   
  geom_text(aes(x=2020.75, y=175, label = sprintf(" %.1f, %.1f%%", labs$chang[1], labs$chng.percent[1]), colour=labs$model[1]), hjust=1, show.legend = FALSE)   
  geom_vline(xintercept = unique(df$year))   
  scale_x_continuous(breaks = c(2020,2021), labels=c(2020, 2021))   
  coord_cartesian(xlim=c(2019.75, 2021.25))   
  theme_minimal()   
  theme(axis.text.y = element_blank(), 
        axis.ticks.y = element_blank(), 
        panel.grid = element_blank())   
  labs(colour ="", y="", x="")

Created on 2022-05-12 by the reprex package (v2.0.1)

  • Related