ggplot2 图例中 shape 填充不显示如何解决
数据小陈
结论
图例里没有填充,问题不在 geom_point()。shape 图例只管 shape 这一个 aesthetic,fill 属于另一个 scale/guide。只在 fill 图例里写 override.aes(shape = 21),不会影响 shape 图例。要让 shape 图例中的 21/23 显示为实心,需要在 shape 的 guide_legend() 里同时 override shape 和 fill,必要时再 override color。override 的向量长度要与 shape 图例项数一致,顺序也要和 scale_shape_manual() 的 breaks/levels 对齐。
原因
shape = interaction(technology, comparison)对应 4 个图例键,scale_shape_manual(values = c(1, 5, 21, 23))按这 4 个键分配形状。fill = type是独立的 fill scale;shape图例默认不继承fill图例的 key。- 对 21/23 这类 filled shape,内部颜色由
fill控制,边框由color控制。只设置shape = c(1,5,21,23)时,21/23 的 fill 可能为NA或不可见。 color = 'none'只关闭 color 图例,不会把 fill 自动加到 shape 图例里。
解决步骤
- 先确认 shape 图例键顺序:
shape_levels <- levels(with(precision_recall, interaction(technology, comparison)))
shape_levels
- 在
guides(shape = guide_legend(...))的override.aes中加入fill和color。例如假设第 3、4 个键是 21/23:
guides(
shape = guide_legend(
title = 'technology comp.',
ncol = 2,
position = 'inside',
order = 3,
title.position = 'top',
title.hjust = .5,
override.aes = list(
shape = c(1, 5, 21, 23),
fill = c(NA, NA, 'grey70', 'grey40'),
color = 'black',
size = 4
)
),
fill = guide_legend(
ncol = 3,
position = 'inside',
order = 1,
title.position = 'top',
title.hjust = .5,
override.aes = list(shape = 21, size = 4)
),
alpha = guide_legend(
ncol = 2,
position = 'inside',
order = 2,
title.position = 'top',
title.hjust = .5,
override.aes = list(size = 4)
),
color = 'none'
)
- 如果想让 21/23 使用
scale_fill_manual()中的颜色,shape guide 不会自动读取 fill scale 的值。需要在 override 中写明确颜色,或者使用与 fill 图例一致的色值:
fill_cols <- ltc('trio1')
shape_fill <- c(NA, NA, fill_cols[1], fill_cols[2])
注意,这只是给 shape 图例里的 21/23 指定一个固定填充色,并不表示每个 shape 键下所有 type 的填充色都能同时显示。
如果希望 shape 图例同时表达 type 填充色
单个 shape 图例无法让一个 shape 键同时显示多个 type 的填充色,因为一个图例键只对应一个 shape 水平;而同一个 technology + comparison 形状下可能有多个 type。这时有两种做法:
- 保留现在的 fill 图例来显示 type 的颜色,shape 图例只用中性填充色表示空心/实心形状;
- 或者把 shape 和 fill 合并成一个新的组合变量(例如
interaction(technology, comparison, type)),再为组合变量统一设置 shape/fill,但图例项会变多,需要手动控制。
注意事项
override.aes的向量长度要和该 guide 的 key 数量一致;长度不对会出现回收或错位。- 21/23 的填充色由
fill控制,边框由color控制;只改shape不够。 legend.position.inside需要较新的 ggplot2 版本;如果报错,先升级 ggplot2 或改用legend.position = c(...)。- 如果 shape 图例中 21/23 仍然看不见,先临时去掉
alpha或把它设为 1 排查透明度影响。
备注:内容仅供参考。
