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

如何将Seaborn生成图表的图例移动到图表外部或右侧?

解决方法

你可以通过获取jointplot返回的JointGrid对象,手动调整图例的位置,同时给右侧留出足够的显示空间,修改后的代码如下:

import seaborn as sns
import matplotlib.pyplot as plt

# 原有数据读取逻辑保持不变
data = Table.read_table('IndiaStatus.csv')
data2 = data.to_df()
data3 = data2.set_index("State/UTs")
print(data3[["Discharged","Total Cases"]])

# 接收jointplot返回的网格对象
g = sns.jointplot(x = "Total Cases", y = "Death Ratio (%)" , data = data, hue = "State/UTs")

# 将图例移动到图表右侧并垂直居中
g.legend.set_bbox_to_anchor((1.3, 0.5))
# 可选:给图例添加明确标题
g.legend.set_title("States/UTs")
# 调整绘图区域边界,给图例留出足够空间避免被截断
plt.subplots_adjust(right=0.78)

plt.show()

参数调整说明

  • 你可以根据实际显示效果微调bbox_to_anchor的第一个数值,数值越大图例越靠右;第二个数值控制垂直位置,0.5代表和绘图区域垂直居中对齐
  • 调整subplots_adjust的right参数,数值越小,绘图区域占比越小,右侧留给图例的空白越多,适合显示长名称的图例条目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:54:03