[英]How to change location of labels of pie chart in ggplot?
I am using this solution here: Adding values and percentages to pie chart我在这里使用这个解决方案: 将值和百分比添加到饼图
But my % are in the wrong place.但是我的 % 是在错误的地方。 How do I fix?
我该如何解决?
# Create dataframe of data
df = data.frame("Sectors" = c("Agriculture", "Industry", "Services"), # labels for your data
"Values" = c(14.9, 48.0, 37.1)) # values of your data
display_color = c("#EB984E", "#1ABC9C", "#95A5A6") # colors for slices
# Create bar plot
g = ggplot(df, aes(x = "",
y = Values, # values for your slices
fill = Sectors
)
)
g = g + geom_bar( # change the color of the slices
width = 1, # change width of bar
stat = "identity",
fill = display_color
)
# CONVERT TO PIE CHART
g = g + coord_polar("y",
start = 0)
g = g + labs(x = NULL, y = NULL, fill = NULL, title = "GDP By Sector")
g
g = g + theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.title = element_text(hjust = 0.5,
color = "#000000"),
panel.background = element_blank()
)
g = g + geom_text(aes(label = paste0(scales::percent(values / sum(values)))),
position = position_stack(vjust = .1))
g
The best thing to do is to remove the coord_polar()
and see where the labels end up.最好的办法是删除
coord_polar()
并查看标签的最终位置。 That usually gives you a sense of what is wrong:这通常会让你知道哪里出了问题:
In this case, your labels are in the wrong order.在这种情况下,您的标签顺序错误。 If you add
rev()
to your labels, now we get the labels in the right order.如果您将
rev()
添加到标签,现在我们会按正确的顺序获取标签。
g = g + geom_text(aes(label = rev(paste0(scales::percent(Values / sum(Values))))),
position = position_stack(vjust = .1))
Here is the full pi chart.这是完整的 pi 图表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.