如何在r中使用ggplot设置饼图中标签的不同字体颜色

如何在r中使用ggplot设置饼图中标签的不同字体颜色,r,ggplot2,R,Ggplot2,饼图中用于标签的项目的数量和百分比,如何使用不同的颜色设置数量和百分比?现在我将它们粘贴到一个字符串中,如果单独使用,我想我可以将它们设置为不同的颜色,但是位置很难调整 这是我的代码: library(ggplot2) library(dplyr) library(cowplot) #data c_title<-data.frame(titles=c("Prof", "Asso Prof","Lecture","Primary"), nums=c

饼图中用于标签的项目的数量和百分比,如何使用不同的颜色设置数量和百分比?现在我将它们粘贴到一个字符串中,如果单独使用,我想我可以将它们设置为不同的颜色,但是位置很难调整

这是我的代码:

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
库(ggplot2)
图书馆(dplyr)
图书馆(cowplot)
#资料

c_title好的,使用两个独立的
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))
库(ggplot2)
图书馆(dplyr)
图书馆(cowplot)

你是说每个标签都是分开的吗?或者黑色的数字和红色的百分比?没错。黑色的数字和红色的百分比。看看这里的第二个答案。。。他使用的是
annotate
,实际上你可以这样做。我使用了两个annotate或geom_text函数,但看起来很难看,这是一个替代解决方案