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

固定figsize下,如何让pandas堆叠柱状图完整显示右侧图例

Fixing Clipped Legend in Pandas Stacked Bar Chart (Fixed Figsize)

我太懂这个坑了——把图例移到右侧后直接被裁剪,还得保持整体figsize固定,对吧?问题根源是默认的子图布局没给图表外的图例留出空间,咱们只需要调整一下子图的边距或者布局参数就能解决,给你几个实用方案:

Method 1: Adjust Subplot Right Margin

用plt.subplots_adjust()手动把图表区域向左缩,给图例腾出位置:

import pandas as pd
import matplotlib.pyplot as plt

data = [ ['Sted 1',9,101,30,50,23,30], ['Sted 2',-13,83,31,44,36,31], ['Sted 3',17,93,22,42,23,35], ['Sted 4',-6,89,24,41,34,29] ]
headers = [ 'Sted', 'Køb af grise og andre indægter', 'Foderomkostninger', 'Dyrlæge, medicin og diverse', 'Arbejdsomkostninger', 'Energi, vedl. bygn. mv.', 'Forrentning driftskapital og øvrige omk.' ]
df = pd.DataFrame(data, columns=headers)
df = df.set_index('Sted')

df.plot(kind='bar', stacked=True, rot=0, figsize=(10,6), legend=False, zorder=3)
plt.grid(zorder=0)
# 把子图右边缘设为figure宽度的80%,剩下的空间给图例
plt.subplots_adjust(right=0.8)
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
plt.show()

你可以根据图例的长度微调right的值——如果图例文字更长,就把这个值调小一点(比如0.75),直到图例完整显示。

Method 2: Use Tight Layout with Custom Bounds

tight_layout()能自动调整子图间距,通过rect参数指定布局的有效区域,专门给图例留位置:

# 前面的代码和上面一致,替换subplots_adjust为这行
plt.tight_layout(rect=[0, 0, 0.8, 1])
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
plt.show()

rect=[0, 0, 0.8, 1]里的四个数分别是左、下、右、上的位置比例,这里把右侧限制在0.8,相当于给图例留了20%的宽度空间。

Method 3: Fine-Grained Control with Figure/Axes Objects

如果想更精准控制图表区域,先创建figure和axes对象,再指定绘图的axes,然后调整axes的位置:

fig, ax = plt.subplots(figsize=(10,6))
df.plot(kind='bar', stacked=True, rot=0, legend=False, zorder=3, ax=ax)
ax.grid(zorder=0)
# [左偏移, 下偏移, 宽度占比, 高度占比],都是0-1的比例
ax.set_position([0.1, 0.1, 0.7, 0.8])
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
plt.show()

这种方式适合需要自定义布局细节的场景,你可以随便调整图表的位置和大小,完美适配图例。

这三种方法都能在保持figsize=(10,6)不变的前提下,让图表自动适配图例宽度,再也不会出现裁剪问题啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:55:54