如何在ggplot2图例中用空格替换下划线?

Rod*_*hew 2 r ggplot2

我的输入 csv 文件(“genus_counts.csv”)的前几行如下所示

Sample,Woeseia,Candidatus_Nitrosopumilus,Nitrospira,Nitrospina,Pseudahrensia,AqS1,Salinicola,Pir4_lineage,Subgroup_10,BD1-7_clade,Sva0996_marine_group,Anoxybacillus,Others,Unclassified
BW1,1.73959,0.474433,0,1.15973,0,0,3.32103,0,0,0,0,8.69794,27.464423,57.1429
BW2,0.424628,0.679406,0,0,0,0,9.95754,0,0.191083,0,1.18896,0,35.7749522,51.7834
Run Code Online (Sandbox Code Playgroud)

我打算基于此制作一个堆积条形图。我尝试了下面的 R 代码,但图例上的名称仍然带有下划线。我引入了该行pcm %>% rename_all(~gsub("_", " ", .)),以便用空格替换所有下划线,但图例上没有任何更改(下划线保留在绘图上!)。任何帮助将不胜感激。

library(ggplot2)
library(reshape2)
pc = read.csv("genus_counts.csv", header = TRUE)
pcm = melt(pc, id = c("Sample"))
pcm$Sample <- factor(pcm$Sample,levels=unique(pcm$Sample))
pcm %>% rename_all(~gsub("_", " ", .))
mx = ggplot(pcm, aes(x = Sample, fill = variable, y = value)) + 
    geom_bar(stat = "identity", colour = "black") + 
    theme(axis.text.x = element_text(angle = 90, size = 14, colour = "black", vjust = 0.5, hjust = 1, face= "bold"), 
    axis.title.y = element_text(size = 16, face = "bold"), legend.title = element_text(size = 16, face = "bold"), 
    legend.text = element_text(size = 12, face = "bold", colour = "black"), 
    axis.text.y = element_text(colour = "black", size = 12, face = "bold")) + 
    scale_y_continuous(expand = c(0,0)) + 
    labs(x = "", y = "Relative Abundance (%)", fill = "Taxon") + 
    scale_fill_viridis_d(option="plasma")
mx
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 5

rename_all用于更改函数的列名称。数据框之后,melt变量不再是列名,而是variable列的值。

因此,您可以在步骤rename_all之前使用melt,也可以mutate在熔化数据框后替换语句中的值。

library(dplyr)
library(ggplot2)

pcm %>%
  mutate(variable = gsub("_", " ", variable)) %>%
  ggplot(aes(x = Sample, fill = variable, y = value)) + 
  geom_bar(stat = "identity", colour = "black") + 
  theme(axis.text.x = element_text(angle = 90, size = 14, 
          colour = "black", vjust = 0.5, hjust = 1, face= "bold"), 
        axis.title.y = element_text(size = 16, face = "bold"), 
          legend.title = element_text(size = 16, face = "bold"), 
        legend.text = element_text(size = 12, face = "bold", colour = "black"), 
        axis.text.y = element_text(colour = "black", size = 12, face = "bold")) +
  scale_y_continuous(expand = c(0,0)) + 
  labs(x = "", y = "Relative Abundance (%)", fill = "Taxon") + 
  scale_fill_viridis_d(option="plasma")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述