Home > Mobile >  Bar plot with count on yaxis and year on x axis with 2 color groups
Bar plot with count on yaxis and year on x axis with 2 color groups

Time:12-09

This will probably be very easy for someone who knows ggplot2, so maybe someone can do a quick plot for me :) Here is an example data and description of what I want to get.

    Year <- c(1991, 1992,1995,1991,1992,1992)
    Type <- c("B", "B", "D", "D", "D", "D")
    df <- data.frame(Year, Type)
    df
  Year Type
1 1991    B
2 1992    B
3 1995    D
4 1991    D
5 1992    D
6 1992    D

I would like to create a barplot with ggplot2 where on X-axis I have separate years, on Y-axis the count of years like there are 3 1992 and put split the bar in color for B and D. I guess I somehow have to count the no. of same years in a group and then add it to the data frame, but I have no clue how to do it.

CodePudding user response:

df1 <-df %>% 
  count(Year, Type) %>%
  mutate(Freq = n/sum(n))

ggplot(df1, aes(x=Year, y=Freq, fill=Type))   
  geom_bar(stat="identity")   
  geom_text(aes(label=scales::percent(Freq)), position = position_stack(vjust = .5)) 
  theme_classic()   
  labs(title = "", x = "Year", y = "%", fill="Type")   
  scale_fill_discrete(name= "Type")

enter image description here

or you can use count(Year, Type)

df1 <-df %>% 
  count(Year, Type) 


ggplot(df1, aes(x=Year, y=n, fill=Type))   
  geom_bar(stat="identity")   
  geom_text(aes(label=n), position = position_stack(vjust = .5)) 
  theme_classic()   
  labs(title = "", x = "Year", y = "Count", fill="Type")   
  scale_fill_discrete(name= "Type")

enter image description here

  • Related