我想将标签放在饼图上,而不是在图例中。换句话说,我希望派对的名称显示在图表的中心而不是右边。我该怎么做?
样本DF:
> data_party$party[1:20]
[1] "Independents" "Independents" "Independents" "Independents" "Democrats"
[6] "Democrats" "Democrats" "Democrats" "Independents" "Independents"
[11] "Democrats" "Democrats" "Democrats" "Democrats" "Democrats"
[16] "Independents" "Democrats" "Democrats" "Independents" "Democrats"
来自列的样本载体:
# pie graph for party
data_party <- subset(data, subset=!is.na(data$Q7))
data_party$party[data_party$Q7==1]<-"Democrats"
data_party$party[data_party$Q7==2]<-"Republicans"
data_party$party[data_party$Q7==3]<-"Independents"
data_party$party[data_party$Q7==4]<-"None"
pie <- ggplot(data_party, aes(x = "Party Affiliation", fill = factor(party))) + geom_text(aes(y = party, label=party)) + geom_bar(width = 1) + theme(panel.background = element_blank())
pie + coord_polar(theta = "y") + theme(legend.title=element_blank())+ theme(axis.title.x = element_blank()) + theme(axis.title.y = element_blank())
答案 0 :(得分:2)
以下是使用grid.text
包中的gridExtra
函数的一种可能解决方案。
#Reproducible example
party = c("None","Republicans","Republicans","Independents","Democrats",
"Democrats","Republicans","Republicans","Independents","Independents",
"Democrats","Democrats","Republicans","Democrats","Democrats",
"Independents","Democrats","Democrats","Republicans","None")
data_party = data.frame(party=party)
#Pie chart without labels
pie = ggplot(data_party, aes(x="", fill=factor(party))) +
geom_bar(width=1) +
coord_polar(theta="y",start=0) +
geom_text(aes(y="",label="")) +
xlab("") + ylab("") +
theme_bw() +
theme(legend.position = "none",
panel.grid.major = element_line(color="grey60"),
panel.border=element_blank())
pie
#Percentage of each category
Democrats = (sum(data_party$party=="Democrats")/length(data_party$party))*100
Democrats = paste("(",Democrats,"%)",sep="")
Republicans = (sum(data_party$party=="Republicans")/length(data_party$party))*100
Republicans = paste("(",Republicans,"%)",sep="")
Independents = (sum(data_party$party=="Independents")/length(data_party$party))*100
Independents = paste("(",Independents,"%)",sep="")
None = (sum(data_party$party=="None")/length(data_party$party))*100
None = paste("(",None,"%)",sep="")
#Add labels with % in pie chart
library(gridExtra)
grid.text(paste("Democrats" ,Democrats ,sep=" "), x=unit(0.62, "npc"), y=unit(0.66, "npc"), gp=gpar(fontsize=14, col="black"), rot = 00)
grid.text(paste("Republicans" ,Republicans ,sep=" "), x=unit(0.40, "npc"), y=unit(0.66, "npc"), gp=gpar(fontsize=14, col="black"), rot = 00)
grid.text(paste("Independents",Independents,sep=" "), x=unit(0.52, "npc"), y=unit(0.27, "npc"), gp=gpar(fontsize=14, col="black"), rot = 00)
grid.text(paste("None" ,None ,sep=" "), x=unit(0.35, "npc"), y=unit(0.38, "npc"), gp=gpar(fontsize=14, col="black"), rot = 36)