【发布时间】:2018-01-08 16:39:42
【问题描述】:
虽然我知道有一些关于这个问题的帖子,但我仍然无法弄清楚如何对饼图的楔形进行排序并将它们与相应的标签相匹配。
我有以下数据集(称为绘图仪数据):
Code Percentage
a 21,43
b 21,43
c 3.58
d 21,43
e 3.58
f 14.29
g 3.58
h 7.14
i 3.58
按照这篇文章 (adding-percentage-labels-on-pie-chart-in-r) 的想法,我开发了以下代码:
library(ggplot2)
library(dplyr)
library(ggforce)
library(scales)
library(ggrepel)
plotter.data<-read.csv("plotter analysis.csv",header=T)
plotter.data$Code<-factor(plotter.data$Code)
plotter.data$Percentage<-round(plotter.data$Percentage, 2)
plotter.data<-plotter.data %>%
arrange(desc(Code))%>%
mutate(text_y = cumsum(Percentage) - Percentage/2)
plotter.data
plotter.plot<ggplot(data=plotter.data,aes(x=1,y=Percentage,fill=reorder(Code,-Percentage)))+
geom_bar(stat = "identity",color='black')+
geom_label_repel(aes(label = percent(Percentage/100),y = text_y), size=3, show.legend = F, nudge_x = 1)+
guides(fill = guide_legend(title = "Code"))+
coord_polar("y",start=0)+
labs(x='',y='',title='Code Plotter systems')+
theme(plot.title=element_text(hjust=0.5,face='bold',size=16))+
theme(axis.text.x=element_blank(),
axis.text.y=element_blank(),
legend.title=element_text(size=12,face='bold'))
plotter.plot
正如您在图中看到的那样,楔形的顺序是正确的,因为我在 ggplot 代码中使用 reorder() 重新排列了我的级别,但是我的标签 (text_y) 不遵循相同的顺序命令。我曾尝试在制作ggplot 之前订购数据集,但仍然无法正常工作。我想知道您是否可以让我知道为什么标签以不同的顺序出现以及如何解决它。
我也尝试在订购数据框之前和之后计算text_y,但一旦使用 ggplot,标签仍然出现在不同的位置。
非常感谢您的建议
【问题讨论】:
-
在 ggplot 中对饼图楔形进行排序与对条形排序完全相同。请参阅r-faq about ordering bars in ggplot。您只需要以正确的顺序设置因子的水平。
reorder()对此非常有用 - 尽管因为您使用的是forcats(或至少加载它,但您似乎根本没有使用它),可能还有其他选项。 -
感谢您的回答@Gregor。我已经更新了我的问题。在发布我的询问之前尝试使用
order()和reorder()。虽然我知道如何订购楔子,但我不明白为什么标签以不同的顺序出现(见新图片)。这就是我不知道如何解决的问题。对不起,如果我的问题不够清楚。再次感谢
标签: r ggplot2 pie-chart labels