项目的数量和百分比用于饼图中的标签,如何使用不同的颜色设置数字和百分比?现在我将它们粘贴成一个字符串,如果单独使用它们,我想我可以将它们设置为不同的颜色,但是位置很难调整。
这是我的代码:
library(ggplot2)
library(dplyr)
library(cowplot)
#data
c_title<-data.frame(titles=c("Prof", "Asso Prof","Lecture","Primary"),
nums=c(20,25,10,5))
c_title$titles<-factor(c_title$titles,levels = c("Primary","Lecture", "Asso Prof","Prof"))
c_title$Percentage<-sprintf("%.1f",c_title$nums/sum(c_title$nums)*100) #percengate
c_title$pie_text<- paste(c_title$Percentage,"%",sep="") #percengate%
c_title$num_p<-paste(c_title$nums,c_title$pie_text,sep="\n")
#plot
ggplot(data = c_title, aes(x = "", y = nums, fill = titles)) +
geom_bar(stat = "identity",width = 1) +
geom_text(aes(label = num_p), position = position_stack(vjust = 0.5),color="red") +
# geom_text(aes(label = nums), position = position_stack(vjust = 0.3))+
coord_polar(theta = "y",direction = -1)+
labs(x ="", y = "", title = "") + #
theme(axis.line = element_blank())+ #remove the axis
theme(axis.ticks = element_blank(),axis.text = element_blank(),
legend.position=c(0.2,0),legend.justification=c(0,1)) +#remove the -
guides(fill=guide_legend(title = NULL,nrow=1)) #remove title of legend
答案 0 :(得分:0)
好的,使用两个独立geom_text
并使用y轴上的绝对位置怎么样?像
library(ggplot2)
library(dplyr)
library(cowplot)
c_title<-data.frame(titles=c("Prof", "Asso Prof","Lecture","Primary"),
nums=c(20,25,10,5))
c_title$titles<-factor(c_title$titles,levels = c("Primary","Lecture", "Asso Prof","Prof"))
c_title$Percentage<-sprintf("%.1f",c_title$nums/sum(c_title$nums)*100) #percengate
c_title$pie_text<- paste(c_title$Percentage,"%",sep="") #percengate%
c_title$num_p<-paste(c_title$nums,c_title$pie_text,sep="\n")
c_title$cumsum <- cumsum(c_title$nums)-c_title$nums/2
#plot
ggplot(data = c_title, aes(x = "", y = nums, fill = titles)) +
geom_bar(stat = "identity",width = 1) +
geom_text(aes(label = nums, y=cumsum, x=0.95),color="red") +
geom_text(aes(label = pie_text, y=cumsum, x=1.05),color="black") +
# geom_text(aes(label = nums), position = position_stack(vjust = 0.3))+
coord_polar(theta = "y",direction = -1)+
labs(x ="", y = "", title = "") + #
theme(axis.line = element_blank())+ #remove the axis
theme(axis.ticks = element_blank(),axis.text = element_blank(),
legend.position=c(0.2,0),legend.justification=c(0,1)) +#remove the -
guides(fill=guide_legend(title = NULL,nrow=1))