作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我输入的 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")
关于r - 如何用ggplot2图例中的空格替换下划线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71546391/
我是一名优秀的程序员,十分优秀!