Home > Back-end >  Making a stacked bar chart with ggplot
Making a stacked bar chart with ggplot

Time:11-23

I'm stuck on how to get a stacked bar chart that shows the yes and no votes on a ballot measure in this election data. Here's the dataframe I'm using and the code I have so far that shows just the no votes

pre <- c("Del Mar Heights","Rancho Penasquitos","La Jolla","Mira Mesa","Miramar")
yes_on_b <- c(7533,16607,6243,10200,443)
no_on_b <- c(8477,20478,8406,10054,356)

ggplot(measure_b_result, aes(pre,no_on_b))  
  geom_bar(stat="identity",fill="steelblue")

CodePudding user response:

Get the data in long format which will make it easier to plot. You may use pivot_longer to do that.

library(tidyverse)

measure_b_result %>%
  pivot_longer(cols = -pre) %>%
  ggplot(aes(pre,value, fill = name))  
  geom_col()   
  labs(x = "Pre", y = "Number of votes", fill = "Type")

enter image description here

  • Related