You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot中让两个映射属性共用同一个图例展示?

在查阅有序数据的相关绘图资料时,我找到了展示两个有序变量关系的示例图:
示例图

我发现现有绘图的图例存在冗余:尺寸和颜色两个视觉映射都对应同一个频数变量,比如频数为10的取值始终对应小尺寸且浅颜色的正方形,其余取值规律一致,不需要拆分成两个独立图例。我预期的绘图图例样式如下:
预期效果图

复现现有绘图的R代码如下:

# DATA
importance <- rep(1:5, times = c(30, 42, 75, 93, 60))
often <- c(rep(1:5, times = c(15, 07, 04, 03, 01)), #n=30, importance 1
           rep(1:5, times = c(10, 14, 12, 03, 03)), #n=42, importance 2
           rep(1:5, times = c(12, 23, 20, 13, 07)), #n=75, importance 3
           rep(1:5, times = c(16, 14, 20, 30, 13)), #n=93, importance 4
           rep(1:5, times = c(12, 06, 11, 17, 14))) #n=60, importance 5
running.df <- data.frame(importance, often)
runningcounts.df <- as.data.frame(table(importance, often))

# PLOT
theme_nogrid <- function (base_size = 12, base_family = "") {
  theme_bw(base_size = base_size, base_family = base_family) %+replace% 
    theme(panel.grid = element_blank())   
}

ggplot(runningcounts.df, aes(importance, often)) +
  geom_point(aes(size = Freq, color = Freq, stat = "identity", position = "identity"), shape = 15) +
  scale_size_continuous(range = c(3,15)) + 
  scale_color_gradient(low = "white", high = "black") +
  theme_nogrid()

解决方法

ggplot在两个视觉映射对应同一变量时,只要给对应的scale设置完全一致的名称、断点,就会自动合并图例,修改后的绘图代码如下:

ggplot(runningcounts.df, aes(importance, often)) +
  geom_point(aes(size = Freq, color = Freq), shape = 15, stat = "identity", position = "identity") +
  # 两个scale统一图例名称、断点,触发自动合并
  scale_size_continuous(name = "频数", range = c(3,15), breaks = c(5,10,15,20,25,30)) + 
  scale_color_gradient(name = "频数", low = "white", high = "black", breaks = c(5,10,15,20,25,30)) +
  # 调整图例标识为正方形,和点样式保持一致
  guides(size = guide_legend(override.aes = list(shape = 15)),
         color = guide_legend(override.aes = list(shape = 15))) +
  theme_nogrid()

运行代码后即可得到图例合并的预期效果。

内容的提问来源于stack exchange,提问作者user11538509

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:36:02