chintan s
chintan s

Reputation: 6488

ggplot2: plot correct proportions using geom_bar

I am trying to plot proportion of diamonds using geom_bar and position = "dodge". Here is what I have done.

library(ggplot2)

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

The image below tell me how many diamonds are there for each cut type.

enter image description here

Now let's do something fancy.

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")

The image below provides count of by grouping diamonds by clarity for each cut type.

enter image description here

What I would like to do is get the same dodge plot as above but showing proportion instead of count.

For example, for cut=ideal and clarity = VS2, the proportion should be 5071/21551 = 0.23.

Upvotes: 0

Views: 3823

Answers (2)

Roman
Roman

Reputation: 17648

You can try

library(tidyverse)
diamonds %>%
  count(cut, clarity) %>% 
  group_by(cut) %>% 
   mutate(Sum=sum(n)) %>% 
   mutate(proportion = n/Sum) %>% 
  ggplot(aes(y=proportion, x=cut,fill=clarity)) +
   geom_col(position = "dodge")

enter image description here

Upvotes: 5

Wimpel
Wimpel

Reputation: 27732

create a column with the correct percentages (named "percentage"), and use

require(ggplot2)
require(scales)

ggplot(data = diamonds) + 
geom_bar(mapping = aes(x = cut, y = percentage, fill = clarity), position = "dodge") + 
scale_y_continuous(labels = scales::percent)

You can also calculate the percentage inline, as Maurits Evers suggests.

Upvotes: -1

Related Questions