ggplot合并形状与颜色图例仅绘制部分数据集的问题咨询
问题原因
你的代码出现仅部分点绘制的核心原因是:
- 你将
shape和color映射到了合并后的LegendGroup变量,但手动传入的values参数长度与LegendGroup的唯一水平数不匹配,ggplot无法为所有观测匹配到对应的形状、颜色参数,会自动丢弃不匹配的观测 - 你按19行观测的顺序传入了19个形状/颜色值,但ggplot会按
LegendGroup水平的字母顺序匹配参数,导致匹配完全错位
调整方案
方案1:按原始需求映射(推荐)
你最初要求Sample列控制点的形状、Feature列控制点的颜色,无需合并为LegendGroup,分开映射逻辑更清晰,图例也更易读:
library(ggplot2) library(RColorBrewer) # 提取唯一值个数 n_sample <- length(unique(SenAssuncao$Sample)) n_feature <- length(unique(SenAssuncao$Feature)) # 分配形状:每个Sample对应一个形状 sample_shapes <- c(17,15,18,20) names(sample_shapes) <- unique(SenAssuncao$Sample) # 分配颜色:每个Feature对应一个颜色 feature_colors <- colorRampPalette(brewer.pal(11, "Set3"))(n_feature) names(feature_colors) <- unique(SenAssuncao$Feature) ggplot(SenAssuncao) + geom_point(aes(x= Al2O3, y= MgO, shape = Sample, colour = Feature), size = 2) + ylab("MgO (wt%)") + xlab("Al₂O₃ (wt%)") + scale_y_continuous(labels=function(x) format(x, scientific = FALSE)) + scale_color_manual(name = "Feature", values = feature_colors) + scale_shape_manual(name = "Sample", values = sample_shapes) + theme(legend.position="right", legend.text = element_text(size = 6), legend.title = element_text(size = 7))
方案2:保留Sample+Feature组合独立映射
如果你确实需要每个Sample+Feature组合对应唯一的形状和颜色,先为唯一水平匹配参数:
library(ggplot2) library(RColorBrewer) SenAssuncao$LegendGroup <- paste(SenAssuncao$Sample, SenAssuncao$Feature, sep = " ") # 提取唯一组合 unique_group <- unique(SenAssuncao$LegendGroup) n_group <- length(unique_group) # 按Sample分配形状:同一样本的所有组合形状一致 group_shapes <- setNames(rep(c(17,15,18,20), table(unique(SenAssuncao[,c("Sample","LegendGroup")])$Sample)), unique_group) # 分配颜色:每个组合对应一个颜色 group_colors <- setNames(colorRampPalette(brewer.pal(11, "Set3"))(n_group), unique_group) ggplot(SenAssuncao) + geom_point(aes(x= Al2O3, y= MgO, shape = LegendGroup, colour = LegendGroup), size = 2) + ylab("MgO (wt%)") + xlab("Al₂O₃ (wt%)") + scale_y_continuous(labels=function(x) format(x, scientific = FALSE)) + scale_color_manual(name = "Sample and Feature", values = group_colors) + scale_shape_manual(name = "Sample and Feature", values = group_shapes) + guides(color = guide_legend(ncol=2)) + theme(legend.position="right", legend.text = element_text(size = 6), legend.title = element_text(size = 7))
内容的提问来源于stack exchange,提问作者jlima.geol
相关产品推荐
相关产品推荐

