如何增强 R 中的分面饼图标签?

How to enhance faceted pie charts labels in R?

我有一个能源数据框,用于记录几年来不同能源的份额:

Year<-c("2016","2016","2016","2017","2017","2017","2018","2018","2018")
Source<-c("coal","hydro","solar","coal","hydro","solar","coal","hydro","solar")
Share<-c(0.5,0.25,0.25,0.4,0.15,0.45,0.7,0.1,0.2)
df<-cbind.data.frame(Year,Source,Share)

多年来,我一直在尝试将数据框绘制为多面饼图:


ggplot(df, aes(x=1, y=Share, fill=Source)) +
  geom_bar(stat="identity", width=1,position="fill")+
  coord_polar("y", start=0) +
  geom_text(aes(label = paste0(round(Share*100), "%")),size=2)+
  labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
  theme_classic() + theme(axis.line = element_blank(),
          axis.text = element_blank(),
          axis.ticks = element_blank(),
          plot.title = element_text(hjust = 0.5, color = "#666666"))+
  facet_wrap(~Year)

我得到以下结果:

如何将标签放在饼图切片之外并以它们的拱形为中心,以及如何为切片添加黑色细边框?我知道饼图不可读,条形图更好一些,但我试图在选项上发挥一些多样性。

非常感谢

饼图基本上是堆叠条形图 - 因此您可以应用相同的规则。代码中的注释。

library(ggplot2)
Year<-c("2016","2016","2016","2017","2017","2017","2018","2018","2018")
Source<-c("coal","hydro","solar","coal","hydro","solar","coal","hydro","solar")
Share<-c(0.5,0.25,0.25,0.4,0.15,0.45,0.7,0.1,0.2)

## don't do that cbind stuff
df<-data.frame(Year,Source,Share)

ggplot(df, aes(x=1, y=Share, fill=Source)) +
  ## geom_col is geom_bar(stat = "identity")(bit shorter)
  ## use color = black for the outline
  geom_col(width=1,position="fill", color = "black")+
  coord_polar("y", start=0) +
  ## the "radial" position is defined by x = play around with the values
  ## the position along the circumference is defined by y, akin to 
  ## centering labels in stacked bar charts - you can center the
  ## label with the position argument
  geom_text(aes(x = 1.7, label = paste0(round(Share*100), "%")), size=2, 
            position = position_stack(vjust = 0.5))+
  labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
  theme_classic() + theme(axis.line = element_blank(),
                          axis.text = element_blank(),
                          axis.ticks = element_blank(),
                          plot.title = element_text(hjust = 0.5, color = "#666666"))+
  facet_wrap(~Year)

reprex package (v2.0.1)

于 2021-12-19 创建