I'm plotting a categorical variable and instead of showing the counts for each category value.
I'm looking for a way to get ggplot
to display the percentage of values in that category. Of course, it is possible to create another variable with the calculated percentage and plot that one, but I have to do it several dozens of times and I hope to achieve that in one command.
I was experimenting with something like
qplot(mydataf) +
stat_bin(aes(n = nrow(mydataf), y = ..count../n)) +
scale_y_continuous(formatter = "percent")
but I must be using it incorrectly, as I got errors.
To easily reproduce the setup, here's a simplified example:
mydata <- c ("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc");
mydataf <- factor(mydata);
qplot (mydataf); #this shows the count, I'm looking to see % displayed.
In the real case, I'll probably use ggplot
instead of qplot
, but the right way to use stat_bin still eludes me.
I've also tried these four approaches:
ggplot(mydataf, aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent');
ggplot(mydataf, aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent') + geom_bar();
ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent');
ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent') + geom_bar();
but all 4 give:
Error: ggplot2 doesn't know how to deal with data of class factor
The same error appears for the simple case of
ggplot (data=mydataf, aes(levels(mydataf))) +
geom_bar()
so it's clearly something about how ggplot
interacts with a single vector. I'm scratching my head, googling for that error gives a single result.
If you want percentage labels but actual Ns on the y axis, try this:
Here is a workaround for faceted data. (The accepted answer by @Andrew does not work in this case.) The idea is to calculate the percentage value using dplyr and then to use geom_col to create the plot.
This is the plot:
Since this was answered there have been some meaningful changes to the
ggplot
syntax. Summing up the discussion in the comments above:Here's a reproducible example using
mtcars
:This question is currently the #1 hit on google for 'ggplot count vs percentage histogram' so hopefully this helps distill all the information currently housed in comments on the accepted answer.
Remark: If
hp
is not set as a factor, ggplot returns:As of March 2017, with
ggplot2
2.2.1 I think the best solution is explained in Hadley Wickham's R for data science book:stat_count
computes two variables:count
is used by default, but you can choose to useprop
which shows proportions.For those coming to this after 2018, replace "labels = percent_format()" with "scales::percent"
Note that if your variable is continuous, you will have to use geom_histogram(), as the function will group the variable by "bins".