如何在R的ggplot双DataFrame柱状图中区分填充与未填充列
解决方案
要实现cell_one对应柱子带填充色、cell_two对应柱子空心(仅保留边框)的效果,你可以拆分两次绘制柱状图,分别控制两组数据的样式:
df$Cell_lines = 'cell_one' data2$Cell_lines = 'cell_two' df3=rbind(df,data2) ggplot(df3, aes(x=Variant_Classification, y=Number_of_Genes)) + # 绘制cell_one的填充柱子,按变异类型区分填充色 geom_bar(data = subset(df3, Cell_lines == 'cell_one'), aes(fill = Variant_Classification), stat="identity", position = 'dodge') + # 绘制cell_two的空心柱子,仅保留边框色 geom_bar(data = subset(df3, Cell_lines == 'cell_two'), aes(col = Cell_lines), fill = NA, stat="identity", position = 'dodge') + theme_minimal() + labs(title ="cell_one vs cell_two") + theme( axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) + # 自定义cell_two的边框色(可选) scale_color_manual(values = c('cell_two' = 'green')) + # 调整填充色图例名称(可选) scale_fill_discrete(name = "Variant Type")
关键修改说明:
- 拆分
geom_bar调用:分别处理两组数据源,避免填充色与边框色的映射冲突 - 对
cell_one保留原有的fill = Variant_Classification映射,维持不同变异类型的填充色区分 - 对
cell_two设置fill = NA让柱子变为空心,同时通过col = Cell_lines设置专属边框色 - 可通过
scale_color_manual自定义边框颜色,scale_fill_discrete调整填充色图例的显示
内容的提问来源于stack exchange,提问作者user17623951
相关产品推荐
相关产品推荐

