我有一個能源資料框,用于多年不同能源的份額:
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)
我得到以下結果:

我怎樣才能把標簽放在餅片的外面并以其拱形居中,我怎樣才能給餅片添加黑色的細邊框?我知道餅圖不可讀,條形圖更好一些,但我試圖在選項中發揮一些不同的作用。
提前謝謝了
uj5u.com熱心網友回復:
餅圖基本上是堆積條形圖 - 因此您可以應用相同的規則。代碼中的注釋。
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 包(v2.0.1)于 2021 年 12 月 19 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/387223.html
上一篇:帶有面板資料的條形圖
