在R中的饼图中添加百分比标签 [英] Adding percentage labels on pie chart in R
问题描述
我的数据框看起来像
df
组值
1正值52
2负239
3中性9
我想制作数据的饼图
pie < - ggplot(df,aes(x =,y = value,fill = Group) ))+
geom_bar(width = 1,stat =identity)+
coord_polar(y,start = 0)
这是我的饼图。
但是,当我尝试在图表上添加百分比标签时
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)]),
lab el = percent(value / 300)),size = 5)
这是我的结果。 p>
我已经看到许多和我一样的问题,即
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.
library(dplyr)
library(ggplot2)
library(ggmap) # for theme_nothing
df <- data.frame(value = c(52, 239, 9),
Group = c("Positive", "Negative", "Neutral")) %>%
# factor levels need to be the opposite order of the cumulative sum of the values
mutate(Group = factor(Group, levels = c("Neutral", "Negative", "Positive")),
cumulative = cumsum(value),
midpoint = cumulative - value / 2,
label = paste0(Group, " ", round(value / sum(value) * 100, 1), "%"))
ggplot(df, aes(x = 1, weight = value, fill = Group)) +
geom_bar(width = 1, position = "stack") +
coord_polar(theta = "y") +
geom_text(aes(x = 1.3, y = midpoint, label = label)) +
theme_nothing()
这篇关于在R中的饼图中添加百分比标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!