饼图中的标签、颜色和切片之间的错误同步

Wrong synchronization between the labels, the colors and the slices in a pie chart

通过运行这个代码:

    g <- ggplot(results_table, aes(x = "", y = Pct*100, 
           fill = factor(results_table$Criteria, as.character(results_table$Criteria))),width = 0.5) +
  geom_bar(stat = "identity") +
  scale_color_manual(values = Palcolor) +
  scale_fill_manual(values = Palcolor) +
  coord_polar(theta = "y", start = 0, direction = -1) +
  theme_minimal() + 
  theme(legend.position = "bottom", legend.title=element_blank(), axis.title.x = element_blank(),, 
        axis.title.y = element_blank(), panel.border = element_blank(), panel.grid = element_blank(),
        axis.text = element_blank(), axis.ticks = element_blank(), 
        plot.title = element_text(size = 14, hjust = 0.5, vjust = 0)) + 
  guides(fill = guide_legend(nrow = 4, byrow = TRUE)) + 
  theme(
    legend.key.height = unit(0.3, "lines"), #smaller squares
    legend.key.width = unit(0.7, "lines"), #smaller squares
    legend.margin=margin(l = 40, unit='pt'),
    legend.text = element_text(margin = margin(r = 60,  unit = "pt"))) +
  xlab("") +  
  ylab("") + 
  geom_text(aes(x = 1.70, y =Pct*100/2 + c(0, cumsum(Pct*100)[-length(Pct*100)]),
                label = paste0(sprintf("%0.1f", round(Pct*100, digits = 1)),"%")),
            size = 3.2) +
  labs(title = gTitle) 

} 我得到这个饼图:

如您所见,切片和颜色是正确的,但标签是反的。如果我使用

position = position_stack (vjust = 0.5, reverse = TRUE)

在 geom_text 中,它将整个馅饼缩小为一小块,然后它没有解决我的问题。

解决方案是用 100 减去 geom_text 中 y 的公式结果:

`geom_text(aes(x = 1.70, y = 100-(Pct*100/2 + c(0, cumsum(Pct*100)[-length(Pct*100)])),
            label = paste0(sprintf("%0.1f", round(Pct*100, digits = 1)),"%")),
            size = 3.2)'