订购饼图片

时间:2018-01-08 16:39:42

标签: r ggplot2 pie-chart labels

虽然我知道在这个问题上有一些帖子我仍然无法弄清楚如何订购饼图的楔形并将它们与相应的标签相匹配。

我有以下数据集(称为绘图仪数据):

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

哪位给我这个数字 enter image description here

正如您在图中所看到的,楔形的顺序是正确的,因为我在reorder()代码中使用ggplot重新排序了我的关卡,但是,我的标签(text_y )不要遵循相同的顺序。我试图在制作ggplot之前订购数据集,但仍然无效。我想知道你是否可以让我知道为什么标签以不同的顺序出现以及如何解决它。

我还尝试在订购我的数据帧之前和之后计算text_y,但是稍后使用ggplot时,标签仍会出现在不同的位置。

非常感谢任何建议

1 个答案:

答案 0 :(得分:1)

在我身边,我设法解决我的问题。一旦根据因子ggplot绘制Code并重新排序我的楔子,我必须使用标签位置(text_y)而不是楔形的值对它们重新排序。

所以:

1-根据您要在数据框中显示因子的顺序命令您

 plotter.data <- plotter.data[order(-plotter.data$Percentage),] 

2 - 计算标签的位置:

plotter.data$text_y <- 100-(cumsum(plotter.data$Percentage) -plotter.data$Percentage/2)

使用reorder()上的ggplot使用标签的位置作为订购可变项:

reorder(Code,-text_y)

因此:

plotter.plot<ggplot(data=plotter.data,aes(x=1,y=Percentage,fill=reorder(Code,-text_y)))+
    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 

enter image description here