chintan s
chintan s

Reputation: 6488

Plot proportion in bar chart grouped by another variable

I am currently reading R for Data Science and trying to create some graphs. I understand that to get proportion in bar chart, you need to use group = 1. For example, the code below works:

library(ggplot2) 

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = color))

But I don't get the same plot for proportions.

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = color, y = ..prop.., group = 1))

I do get proportion but not by color.

Upvotes: 1

Views: 1513

Answers (1)

Mako212
Mako212

Reputation: 7292

Here's one way to do it using ..count..

require(ggplot2)

ggplot(diamonds,aes(cut,..count../sum(..count..),fill=color))+
  geom_bar()+
  scale_y_continuous(labels=scales::percent)

enter image description here

Upvotes: 1

Related Questions