Home > Back-end >  Create a bar chart with proportions
Create a bar chart with proportions

Time:11-17

I am trying to create a bar chart from data that looks similar to this:

bird dr season
ambi 45 molting
ambi 45 molting
ambi 45 molting
ambi 45 breeding
ambi 45 breeding
ambi 45 winter
ambi 45 winter
abum 60 molting
abum 60 molting
abum 60 molting
abum 60 breeding
abum 60 breeding
abum 60 winter
abum 60 winter

I would like all birds listed on the y axis, and I would like the x axis to be dr. I would like the bars to be colored-coded based on proportion of observations from each season. For example, for abum, I would like the bar to reach 0.6, and I would like the bar to be color-coded based on season. abum has 3/7 observations during the molting season, 2/7 during breeding, and 2/7 during winter. I would like the colors in the bar to reflect this. This is the code I have so far:

plot <- ggplot(data=test, aes(x=dr, y=bird, fill=season))  
     geom_bar(stat="identity") 
     scale_fill_brewer(palette="Paired") 
     theme_minimal()

This sets up my birds correctly on the y axis and color codes the bars, but I think it is using some kind of count value as opposed to the dr value on the x axis.

An image of what the code is producing: plot image

The x axis does not reflect the dr values. I am not sure where the x axis values are coming from. I would also like to reverse the order of the birds, so that they are in alphabetical order from top to bottom.

CodePudding user response:

I'm not sure about dr part. If there's something wrong, please let me know.

library(dplyr)
library(ggplot2)
library(forcats)

test %>%
  group_by(bird, season) %>%
  summarise(key = unique(dr),
            dr = sum(dr)) %>%
  group_by(bird) %>%
  mutate(dr = dr/sum(dr) * key/100) %>%
  ungroup %>%
  mutate(bird = fct_reorder(bird, desc(bird))) %>%
  ggplot(aes(x=bird, y=dr, fill=season))  
  geom_bar(stat="identity") 
  scale_fill_brewer(palette="Paired") 
  theme_minimal()  
  coord_flip()

enter image description here

  • Related