Reputation: 6488
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.
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.
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
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")
Upvotes: 5
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