Home > Mobile >  R: Horizontal bar chart to show start year with no end year
R: Horizontal bar chart to show start year with no end year

Time:08-24

I am trying to create a horizontal bar chart, which includes "Year" on the X-axis and "Type" on Y-axis.

Here is an example of my data:

library(ggplot2)

table <- "startyear type
1  2007    AB
2  2007    BB
3  2010    CB
4  2020    AD
5  2015    BD
6  2022    CD"

#Create a dataframe with the above table
df <- read.table(text=table, header = TRUE)
df

I am trying to make the bar start at the year that is associated with the type (e.g. the bar for AB would start at the year 2007 and the bar for CD would start at 2022), but I want every bar to continue up to 2022 (so for this example, the bar for AB would start at 2007 and extend until 2022, whereas CD would only have a line for 2022). In other words, the bar would be longer for types that have an earlier start year. The goal is to show how long we have been using each type, up until the present (2022).

This is what I have come up with so far:

plot <- ggplot(df, aes(x = startyear, y = type))  
  geom_bar(stat="identity", position = "dodge")  
  xlab("Year")  
  ylab("Type")
plot

But all the bars are the same length and start at the same year. Any help would be appreciated!

CodePudding user response:

One simple way to do this would be to subtract 2022 from all the years, and add 2022 to all the x axis labels:

ggplot(df, aes(startyear - 2022, type, fill = type))  
  geom_col(, color = "gray50")  
  scale_x_continuous(labels = ~ .x   2022)  
  scale_fill_brewer(palette = "Pastel2", guide = "none")  
  theme_minimal(base_size = 16)  
  labs(x = "Year")

enter image description here

  • Related