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

ggplot绘图:如何将单列图例拆分为多列?

解决ggplot图例拆分为多列的问题

问题描述

我有一个名为wi_hist_df的数据框,包含三列(部分数据如下):

weights Frequency   Criterion
1  0.2425         2 Criterion_1
2  0.2475        15 Criterion_1
3  0.2525        80 Criterion_1
4  0.2575       314 Criterion_1
5  0.2625       759 Criterion_1
6  0.2675      1296 Criterion_1
...
103  0.0465        29 Criterion_7
104  0.0475        18 Criterion_7
105  0.0485         6 Criterion_7
106  0.0495         2 Criterion_7
107  0.0505         2 Criterion_7
108  0.0515         1 Criterion_7

使用ggplot绘制多准则折线图的代码如下:

weights_ggplot = ggplot(data = wi_hist_df, aes(x = weights, y = Frequency, color = Criterion)) +
    geom_line(size = 1.5) + theme_bw() +
  theme(axis.text.x  = element_text(size = 30),axis.text.y  = element_text(size = 30) )     +
  theme(axis.title.x = element_text(size = 30),axis.title.y = element_text(size = 30) )     +
  theme( legend.title=element_text(size=10),  legend.text=element_text(size=10)       )
weights_ggplot # 需要将图例拆分为多列

希望将默认的单列图例拆分为多列,尝试guides函数未成功,求解决方法。

解决方案

要将ggplot的图例拆分为多列,只需在代码中通过guides()函数指定对应美学(这里是color)的图例格式,使用guide_legend()设置ncol参数即可。以下是修改后的完整代码:

weights_ggplot = ggplot(data = wi_hist_df, aes(x = weights, y = Frequency, color = Criterion)) +
    geom_line(size = 1.5) + 
    theme_bw() +
    theme(
        axis.text.x = element_text(size = 30),
        axis.text.y = element_text(size = 30),
        axis.title.x = element_text(size = 30),
        axis.title.y = element_text(size = 30),
        legend.title = element_text(size = 10),
        legend.text = element_text(size = 10)
    ) +
    # 设置图例为2列,可根据准则数量调整ncol的数值
    guides(color = guide_legend(ncol = 2))

weights_ggplot

补充说明

  • ncol参数可按需调整:比如7个准则设置ncol=3会分成3列(前两列3个、最后一列1个),设置ncol=2则分成4个和3个的两列。
  • 另一种等价写法是直接通过scale_color_discrete()指定图例格式,替换上述代码中的guides()部分即可:
    scale_color_discrete(guide = guide_legend(ncol = 2))
    

若之前使用guides()未成功,大概率是未明确指定对应的美学属性(如color),或是未用guide_legend()包裹列数设置。

内容的提问来源于stack exchange,提问作者ΚΩΝΣΤΑΝΤΙΝΟΣ ΠΑΝΑΓΙΩΤΟΥ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:46:25