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

如何编辑Seaborn散点图的多个图例,调整其位置与命名?

散点图图例调整方案

你需要拆分seaborn自动生成的两个合并图例(分别对应hue参数映射的平均成本、size参数映射的总收入),分别修改标题和放置位置即可,完整修改后的代码如下:

import matplotlib.pyplot as plt
import seaborn as sns

figure = plt.figure(figsize=(10,5))
# 调整图表右侧留白,避免外置图例被截断
plt.subplots_adjust(right=0.8)

ax = sns.scatterplot(
        x=top_rev_mean['cost_of_the_order_y'],
        y='cost_of_the_order_x', 
        data=top_rev_mean, 
        size = "cost_of_the_order_x", 
        hue='cost_of_the_order_y'
    )

plt.ylabel('Total Order Revenue')
plt.xlabel('Average Order Cost Per Cuisine')

# 提取所有图例的句柄和标签
handles, labels = ax.get_legend_handles_labels()
# 移除seaborn自动生成的合并图例
ax.get_legend().remove()

# 计算拆分位置:hue对应标签数等于你设置的hue分组数,可根据实际打印handles长度调整索引
hue_group_num = 4 # 示例值,可根据实际分类数修改
# 生成第一个图例:平均成本,放置在图表外右上角
legend_avg_cost = ax.legend(
    handles=handles[:hue_group_num], 
    labels=labels[:hue_group_num], 
    title='Average Cost', 
    bbox_to_anchor=(1.25, 1), 
    loc="upper left"
)
# 手动添加第一个图例到坐标轴,避免被后续生成的第二个图例覆盖
ax.add_artist(legend_avg_cost)

# 生成第二个图例:总收入,放置在图表外右下角
ax.legend(
    handles=handles[hue_group_num:], 
    labels=labels[hue_group_num:], 
    title='Total Revenue', 
    bbox_to_anchor=(1.25, 0), 
    loc="lower left"
)

plt.show()

注意:如果不确定hue的分类数量,可以执行print(len(handles))打印总句柄数,或者直接打印labels查看标签内容,再调整拆分的索引值即可。

原始参考图:
成本散点图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:18:05