如何用R语言ggplot为物种设不同颜色、性别设不同图案
解决方法
要实现按物种区分颜色、按性别区分填充图案,需要用到ggpattern包(ggplot2原生不支持填充图案),具体修改如下:
- 先安装并加载
ggpattern包:
install.packages("ggpattern") library(ggpattern)
- 修改绘图代码,核心改动是:
- 将
fill映射从sex改为species,实现物种区分颜色 - 用
geom_bar_pattern替代geom_bar,添加pattern = sex映射实现性别区分图案 - 分别设置颜色和图案的自定义样式
完整修改后的代码:
# making bar plot library(readr) library(ggplot2) library(ggpattern) # loading and checking the data data_summary <- read_csv("trial.csv") print(data_summary) # 按物种设颜色、性别设图案的柱状图 ggplot(data_summary, aes(x = factor(species), y = mean, fill = species)) + geom_bar_pattern( stat = "identity", position = "dodge", aes(pattern = sex), # 按性别设置图案 pattern_fill = "black", # 图案线条颜色 pattern_density = 0.1, # 图案密度 pattern_spacing = 0.02, # 图案间距 show.legend = TRUE ) + geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(0.9), width = 0.2) + labs(x="", y="", fill = "物种", pattern = "性别") + # 修改图例标题 theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position = c(0.1, 0.75)) + ylim(0, 80) + scale_fill_manual(values=c("#870A30", "#1E90FF", "#32CD32")) + # 按物种数量自定义颜色 scale_pattern_manual(values=c("stripe", "crosshatch")) # 为不同性别设置图案
关键说明:
- 如果你的物种数量更多,需要在
scale_fill_manual里添加对应数量的颜色值 - 可选的图案样式包括:
stripe(条纹)、crosshatch(交叉线)、dot(圆点)、grid(网格)等,可根据需求替换 pattern_density和pattern_spacing可以调整图案的疏密程度
内容的提问来源于stack exchange,提问作者Woony
相关产品推荐
相关产品推荐

