0

Currently my code below plots the count of cases stratified by columnB and over different years on the x-axis. Instead of actual counts, I would like to plot the proportions of cases. How would I go about and do that?

ggplot(df, aes(x= year, fill=columnB)) + geom_bar()

Thanks!

HubertL
  • 19,246
  • 3
  • 32
  • 51
Y Huang
  • 1
  • 1
  • Possible duplicate of [ggplot: showing % instead of counts in charts of categorical variables](http://stackoverflow.com/questions/3695497/ggplot-showing-instead-of-counts-in-charts-of-categorical-variables) – Heroka Feb 11 '16 at 10:23

1 Answers1

2

You can easily do this by adding

ggplot(df, aes(x= year, fill=columnB)) + geom_bar(position = "fill")

You can refer here

Just modify the answer. Thanks Heroka for pointing out the error of my previous answer.

Community
  • 1
  • 1
MaxGu
  • 71
  • 4
  • Are you sure this works? Doesn't stat=identity need a variable mapped to the y-axis? – Heroka Feb 10 '16 at 14:15
  • Of course it works. If you would like to use explicit mapping, you can rewrite the code as `ggplot(df) + geom_bar(aes(x= year, fill=columnB), stat = "identity")`. You can either write **aes** part in **ggplot()** or in **geom_bar()** because ggplot2 grammar is kind of layer structure, probably you can compare it with photoshop graph layers. – MaxGu Feb 10 '16 at 23:09
  • That's not what I meant at all. I was trying to be polite, but please consider the following code: `df <- data.frame(year=factor(rep(2000:2003, each=5)), columnB=sample(LETTERS[1:5],20,T)); ggplot(df, aes(x = year, fill = columnB)) + geom_bar(stat="identity")`. You will get an error. – Heroka Feb 11 '16 at 10:01
  • @Heroka Oh, Okay. In this case, should use `position = 'fill'` rather than `stat = 'identity'`. Thanks for pointing this out! – MaxGu Feb 11 '16 at 18:30