0

I'm making a simple bar chart but I can't seem to figure it out. I've got my data as laid out here:

Candidate SkinTone Elected
1 7 1
2 4 0
3 3 0
4 2 1

Skin tone refers to a person's skin tone (obvs) and elected is a dummy variable that denotes whether a candidate was elected or not. What I want to do is have every skin tone value (it goes from 1-11) as a tick on my x-axis and my y-axis should be the percentage of those candidates that have a "1" as their elected value. So, for example, this tiny data set should generate a chart that looks like this:

Final Bar Graph

The problem I encounter is that I'm not able to figure out how to get this graph's y-axis correctly. Using this code below, I can generate a graph that looks like the one below:

    ggplot(data=data, mapping = aes(x=Tone, y=Elected)) +
  geom_bar(stat='identity',
           fill="yellow",
           col="black",
           width=1,
           alpha=.2) +
  coord_cartesian(xlim = c(0.5,11.5)) +
  scale_x_continuous(breaks = 1*1:11,
                     expand = expansion(add = .5)) +
  labs(title="Skin Tone Electoral Success Barplot", x="Skin Tone", y="Percentage of Candidates Elected")

Incorrect Bar Graph

However, this doesn't work for me as the y-axis is showing the count of candidates who had a 1 in the Elected variable instead of the percentage. In addition, I'm getting these black blocks in between each observation, which I haven't gotten before when using col=. Lastly, I also find trouble adding in a density line as geom_density() gives me an error saying I'm missing my y aesthetic.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
  • `ggplot(data, aes(SkinTone, Elected)) + geom_bar(stat="identity")`. – Rui Barradas Oct 24 '21 at 19:59
  • Was the error just the misspelling of the column name? – IRTFM Oct 24 '21 at 20:10
  • Also, to have all factor levels (`SkinTone`) use `drop=FALSE`: `scale_x_discrete(breaks = 1:11, drop=FALSE)`. – Rui Barradas Oct 24 '21 at 20:12
  • No, the column name is fine. I just used a diff name by accident when writing this question. I'm still just getting the count of observations that are 1 but I'm hoping to get the percentage of observations that are 1 instead. – falling balloons Oct 24 '21 at 20:13
  • By the way, next time can you provide a reproducible example and also show the graphs, rather than provide links to them? https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – william3031 Oct 24 '21 at 23:05

0 Answers0