gpt4 book ai didi

r - 如何用ggplot2图例中的空格替换下划线?

转载 作者:行者123 更新时间:2023-12-02 01:41:27 24 4
gpt4 key购买 nike

我输入的 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

我打算以此为基础制作堆积条形图。我尝试了下面的 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

最佳答案

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

因此,您可以在 melt 步骤之前使用 rename_all,也可以在熔化数据帧后替换 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")

enter image description here

关于r - 如何用ggplot2图例中的空格替换下划线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71546391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com