将子/上标添加到条形图标签

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将子/上标添加到条形图标签相关的知识,希望对你有一定的参考价值。

我有这个情节

plot.colors<- c("#a6cee3", "#1f78b4","#b2df8a","#33a02c", "#525252")
ggplot() + 
  geom_bar(aes(y = v3, x = v1 , fill = v2), data = melted.data, stat="identity") + 
  coord_flip() + 
  scale_fill_manual(values= plot.colors) + 
  facet_wrap(~v4)

我想在轴刻度上添加子脚本或超级脚本;即:“BRCA ^ a”,“BLCA ^ a,b”和“ACC ^ b”。但我被困住,因为我不知道如何在不改变数据表的情况下改变轴刻度。有没有办法创建一个矢量并使用其元素作为轴刻度?在这种情况下,我想我可以使用类似“as.expression”的东西。

所以这里是图书馆和数据:

library(ggplot2)

v1<- c("ACC", "BLCA", "BRCA", "ACC", "BLCA", "BRCA", "ACC", "BLCA", "BRCA", "ACC", "BLCA", "BRCA", "ACC", "BLCA", "BRCA", "ACC", "BLCA", "BRCA", "ACC", "BLCA", "BRCA", "ACC", "BLCA", "BRCA", "ACC", "BLCA", "BRCA")
v2<- c("LumA", "LumA", "LumA", "LumA", "LumA", "LumA", "LumB", "LumB", "LumB", "LumB", "LumB", "LumB", "Basal", "Basal", "Basal", "Basal", "Basal", "Basal", "Her2", "Her2", "Her2", "Her2", "Her2", "Her2", "NoA", "NoA",  "NoA")
v3<- c(46.575342, 39.726027, 36.120401, 26.027397, 24.931507, 22.965440, 9.589041, 14.794521, 22.073579, 1.369863,  2.191781,  7.580825, 26.027397, 31.506849, 26.198439,  2.739726, 4.931507, 22.742475, 17.808219, 13.972603, 15.607581, 4.109589,  3.013699, 10.256410, 65.753425, 64.931507, 36.454849)
v4<- c("pam50", "pam50", "pam50", "pbcmc", "pbcmc", "pbcmc", "pam50", "pam50", "pam50", "pbcmc", "pbcmc", "pbcmc", "pam50", "pam50", "pam50", "pbcmc", "pbcmc", "pbcmc", "pam50", "pam50", "pam50", "pbcmc", "pbcmc", "pbcmc", "pbcmc", "pbcmc", "pbcmc")

melted.data<- data.frame(v1, v2, v3, v4)
rm(v1, v2, v3, v4)
答案

只需将另外一个命令添加到ggplot中

scale_x_discrete(labels = parse(text=c("BRCA" = "BRCA^a", "BLCA" = "BLCA^{list(a, b)}", "ACC" = "ACC^b")))

这将改变x轴上的刻度

ggplot() + 
  geom_bar(aes(y = v3, x = v1 , fill = v2), data = melted.data, stat="identity") + 
  coord_flip() + 
  scale_fill_manual(values= plot.colors) + 
  facet_wrap(~v4) +
  scale_x_discrete(labels = parse(text=c("BRCA" = "BRCA^a", "BLCA" = "BLCA^{list(a, b)}", "ACC" = "ACC^b")))

enter image description here

以上是关于将子/上标添加到条形图标签的主要内容,如果未能解决你的问题,请参考以下文章

如何将标签添加到堆叠条形图

使用 stat=summary 将标签添加到条形图

tableau每日一技:将标签显示在条形图的柱子上

tableau每日一技:将标签显示在条形图的柱子上

tableau每日一技:将标签显示在条形图的柱子上

将百分比标签添加到堆积条形图ggplot2