My data frame looks like
df
Group value
1 Positive 52
2 Negative 239
3 Neutral 9
I would like to make a pie chart of the data frame using ggplot.
pie <- ggplot(df, aes(x="", y=value, fill=Group)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0)
This is my pie chart.
But when I try to add percentage labels on the chart
pie <- ggplot(df, aes(x="", y=value, fill=Group)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0) +
geom_text(aes(y = value/2 + c(0, cumsum(value)[-length(value)]),
label = percent(value/300 )), size=5)
This is my result.
I have already seen many same question as mine,i.e R + ggplot2 => add labels on facet pie chart and the solutions are not helping.
I agree with @hrbrmstr a waffle chart would be better. But to answer the original question... your problem comes from the order in which the wedges are drawn, which will default to alphabetical. As you calculate where to place the labels based on the ordering in your data frame, this works out wrong.
As a general principle of readability, do all the fancy calculations of labels and positions they go before the actual code drawing the graphic.
How about:
instead?
It's "fresher" than a pie chart and you aren't really gaining anything with the level of precision you have/want on those pie labels now.
Here is an idea matching the order of groups in the pie chart and the order of labels. I sorted the data in descending order by
value
. I also calculated the percentage in advance. When I drew the ggplot figure, I specified the order ofGroup
in the order inmydf
(i.e., Negative, Positive, and Neutral) usingfct_inorder()
. Whengeom_label_repel()
added labels to the pie, the order of label was identical to that of the pie.DATA
For example, I create a dataframe e3 with 400 vehicles:
Since pie charts are especially useful for proportions, let's have a look on the proportions of our vehicles, than we will report on the graph in this case:
Then you can draw your pie chart,