1

I am trying to graph qualitative policy analysis data in R. My database has one row for each policy, and then columns for binary variables, conditions that are coded "1" if that condition is met. Finally, each row also contains a column for whether that policy is mandatory, voluntary, or partial.

I want to create a bar chart that sums the columns, then colors in the bars according to what percentage of the sum is Mandatory, Voluntary, or Partial.

The ideal outcome would be to create a bar chart like the one below, but coded by color according to the ratio of Mandatory, Voluntary, or Partial policies

Policy Bar chart

Here is some sample data in the same format:

df<- data.frame(ID=c(1,2,3,4,5,6),
            policy=c("Policy A", "Policy B", "Policy C", "Policy D", 
            "Policy E","Policy F" ),
            Data_collection= c(1, 0, 0, 1, 1, 0),
            Handling_release= c(0, 1, 0, 1, 0, 1),
            Gear_modification= c(1, 0, 0, 1, 1, 0),
            Stength=c("M", "V", "M", "P", "P", "M"),
            stringsAsFactors=FALSE)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Alyssa C
  • 79
  • 8
  • 3
    Please read this https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Bruno Jan 03 '20 at 22:19
  • 1
    Please share your data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) (we can't copy and paste data from images to test the code). Instead use a picture to maybe sketch what the desired output should look like. It's not clear to me exactly what the desired result is here. – MrFlick Jan 03 '20 at 22:22
  • just edited, I hope that helps! Sorry, I'm new here! :) – Alyssa C Jan 03 '20 at 23:03

1 Answers1

2

It looks like you really need to reshape your data to a proper tidy format to make plotting easier. For example you could do

library(dplyr)
library(tidyr)
library(ggplot2)

df %>% 
  pivot_longer(Data_collection:Gear_modification) %>% 
  filter(value==1) %>% 
  ggplot(aes(name, fill=Stength)) +
  geom_bar()

For the sample data provided this gives

stacked bar plot

For adding the total on top see this existing question: draw the sum value above the stacked bar in ggplot2

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thank you so much! That worked perfectly! wow. One more thing -- I'm trying to line the bars up from high on the left to lowest on the right, is there a way to do that? thank you thank you!! – Alyssa C Jan 03 '20 at 23:35
  • 1
    If you search for “order stacked bar plot” you will probably find useful answers for that problem. Good luck. – MrFlick Jan 03 '20 at 23:42