Reputation: 1548
I can't resolve that strange situation. Somewhere I have error, or bug, but sitting over three halfs of an hour could not deal with it.
I have: sta_df
sta value
1 IN_LIQUIDATION 29
2 LIQUIDATED 47
3 OPERATING 435
4 TRANSFORMED 8
sp <- ggplot(sta_df, aes(x="", y=value, fill=sta)) +
geom_bar(width = 1, stat = "identity", color = "black") +
coord_polar("y") + scale_fill_brewer(palette="Pastel2") +
geom_text(aes(x = seq(1.2,1.4,,4), label = percent(value/sum(value))),
position = position_stack(vjust = 0.5), size=5)
and the plot have wrong direction of labelling.
Nevermind this strange font of a picture. I've tried to use many different functions instead of position_stack
. For example:
geom_text(aes(x = rep(seq(0.9,1.4,,6),1), y = value/2 + c(0, cumsum(value)[-length(value)])
but it didn't help. This thread neither: wrong labeling in ggplot pie chart
When I wanted to reverse y=rev(value)
the legend didn't correspond with data. Putting direction 1
or -1
doesn't do more than reversing all. Reversing values in geom_text
gives Pac-Man-like chart. I've updated ggplot2
.
Honestly, the problem is because chart starts to draw anti-clockwise although direction is set to clockwise and text numbers are in right direction. And reversing data in data.frame doesn't change anything in the whole plot. Sorry, I stuck, but feel the solution is right there.
Upvotes: 2
Views: 2495
Reputation: 14667
The problem occurs when you assign different x-values to your labels in geom_label()
. Why? Because you are relying on position_stack()
to give you your y-values. But when the points no longer share the same x, then they don't get 'stacked' anymore. If you want to customize the x-values, you will need to compute your own y-values, as described here (Showing data values on stacked bar chart in ggplot2) and here (http://docs.ggplot2.org/current/geom_text.html) near bottom of the page. By the way, I did all my troubleshooting with coord_polar
removed, just looking at the plain barplot version.
Anyway, here is a partial solution:
sta_df <- read.table(header=TRUE,
text=" sta value
IN_LIQUIDATION 29
LIQUIDATED 47
OPERATING 435
TRANSFORMED 8")
library(ggplot2)
library(scales)
sta_df$fraction = sta_df$value / sum(sta_df$value)
sp <- ggplot(sta_df, aes(x="", y=value, fill=sta)) +
geom_bar(width=1, stat="identity", color="black",) +
scale_fill_brewer(palette="Pastel2") +
coord_polar(theta="y") +
geom_text(aes(x=1.4, label=percent(fraction)),
position=position_stack(vjust=0.5), size=4)
ggsave("pie_chart.png", plot=sp, height=4, width=6, dpi=150)
Upvotes: 2