如何增强 R 中的多面饼图标签?
Posted
技术标签:
【中文标题】如何增强 R 中的多面饼图标签?【英文标题】:How to enhance faceted pie charts labels in R? 【发布时间】:2022-01-21 12:37:22 【问题描述】:我有几年来不同能源份额的能源数据框:
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)
我得到以下结果:
如何将标签放在饼片之外并使其拱形居中,以及如何在饼片上添加黑色细边框?我知道饼图不可读,而且条形图要好一些,但我正在尝试在选项上玩一些不同的选择。
在此先感谢
【问题讨论】:
【参考方案1】:饼图基本上是堆积条形图 - 因此您可以应用相同的规则。代码中的注释。
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 日创建
【讨论】:
非常感谢@tjebo!祝您节日快乐!以上是关于如何增强 R 中的多面饼图标签?的主要内容,如果未能解决你的问题,请参考以下文章