微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在ggplot2中的图例栏上添加特定数字?

如何解决如何在ggplot2中的图例栏上添加特定数字?

我尝试在ggplot2中绘制barplot,并尝试在图例中添加特定数字。它有效,但是这次我丢失了我的特定颜色(mycolors2),您对我有什么建议?您可以在下面看到我的预期输出(用不同的颜色)。

  df <- data.frame("Var"=c("A","B","C","D"),"IQ"=c(28,32,25,33),"Se"=c(2.1,3.2,4.1,3.5))


   mycolors2<-c(paste0("royalblue",c(4:3)),c("steelblue4","steelblue3"))

p<-ggplot(df,aes(x=Var,y=IQ,fill=Var))+
  geom_bar(stat="identity",color="black")+
  scale_fill_manual(values=mycolors2)+
  geom_errorbar(aes(ymin=IQ-Se,ymax=IQ+Se),width=.2,position=position_dodge(.9))


p

p + coord_cartesian(ylim=c(0,100))+ theme_classic()+
  xlab("Variant Groups")+
  ylab("Comparison of IQ scores for Autism Female Probands with \n ROH Blocks Carrying Variants or No-Variant")+
  theme( axis.title.y = element_text(size = 16,margin = margin(t = 0,r =0,b = 0,l = 4,unit = "mm")),axis.title.x = element_text(size = 16,l = 0,panel.background = element_rect(fill = "white")) +
  scale_fill_discrete(labels = c("A(n=128)","B(n=148)","C(n=223)","D(n=154)"))
  theme_classic()

我期望的其他颜色输出

enter image description here

解决方法

尝试这种方法。与其添加一个新的scale_fill_*()参数,不如将其直接设置为第一个fill选项。这里的代码:

library(ggplot2)
#Data
df <- data.frame("Var"=c("A","B","C","D"),"IQ"=c(28,32,25,33),"Se"=c(2.1,3.2,4.1,3.5))
#Colors
mycolors2<-c(paste0("royalblue",c(4:3)),c("steelblue4","steelblue3"))

地块代码:

#Code
ggplot(df,aes(x=Var,y=IQ,fill=Var))+
  geom_bar(stat="identity",color="black")+
  scale_fill_manual(values=mycolors2,labels = c("A"="A(n=128)","B"="B(n=148)","C"="C(n=223)","D"="D(n=154)"))+
  geom_errorbar(aes(ymin=IQ-Se,ymax=IQ+Se),width=.2,position=position_dodge(.9))

输出:

enter image description here

使用您的整个代码,您将:

#Code 2
ggplot(df,position=position_dodge(.9))+
  coord_cartesian(ylim=c(0,100))+ theme_classic()+
  xlab("Variant Groups")+
  ylab("Comparison of IQ Scores for Autism Female Probands with \n ROH Blocks Carrying Variants or No-Variant")+
  theme( axis.title.y = element_text(size = 16,margin = margin(t = 0,r =0,b = 0,l = 4,unit = "mm")),axis.title.x = element_text(size = 16,l = 0,panel.background = element_rect(fill = "white"))+
theme_classic()

输出:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。