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

如何在seaborn figure-level绘图中为长x轴刻度标签换行或移入侧边图例

解决方案

下面提供两种符合需求的实现方式:


方案1:X轴刻度标签多行展示

通过textwrap给每个刻度标签自动换行,不需要将图表设置得过宽:

import seaborn as sns
import matplotlib.pyplot as plt
from textwrap import wrap
import pandas as pd
import numpy as np
from itertools import chain

# 生成示例数据集
x = (np.repeat('Brake and crash into the bus', 37),
np.repeat('Steer into the passing car on the left', 22),
np.repeat('Steer into the right hand sidewall', 39))
results = pd.DataFrame({'1': list(chain(*x))})

sns.set(style="dark")
catp = (sns.catplot(data=results, x='1',
                    kind='count',
                    hue_order=results.sort_values('1')['1'],
                    palette='crest',
                    height=3.3,
                    aspect=1.8) # 缩小宽高比,不需要过宽
        .set(xlabel=None,
             ylabel='参与人数',
             title="\n".join(wrap("问题1:如果你坐在全自动驾驶汽车中,以下三个选项中,你更希望车辆选择哪种操作?", 90)))
)

# 新增:x轴刻度标签自动换行,每行最多12个字符
labels = [ '\n'.join(wrap(label.get_text(), 12)) for label in catp.ax.get_xticklabels()]
catp.ax.set_xticklabels(labels, fontsize=10)

plt.tight_layout()
catp.ax.set_yticks((0,10,20,30,40))
for p in catp.ax.patches:
    percentage = '{:.1f}%'.format(100 * p.get_height()/92)
    x = p.get_x() + p.get_width() / 2 - 0.05
    y = p.get_y() + p.get_height() + 0.3
    catp.ax.annotate(percentage, (x, y), size = 12)
plt.show()

方案2:将选项标签移至侧边图例

将选项绑定到hue参数,隐藏x轴刻度,长文本全部放在侧边图例中:

import seaborn as sns
import matplotlib.pyplot as plt
from textwrap import wrap
import pandas as pd
import numpy as np
from itertools import chain

# 生成示例数据集
x = (np.repeat('Brake and crash into the bus', 37),
np.repeat('Steer into the passing car on the left', 22),
np.repeat('Steer into the right hand sidewall', 39))
results = pd.DataFrame({'1': list(chain(*x))})

sns.set(style="dark")
catp = (sns.catplot(data=results, 
                    x=pd.Series(['']*len(results)), # x轴设为空白分类
                    hue='1', # 选项绑定到hue
                    kind='count',
                    hue_order=results.sort_values('1')['1'],
                    palette='crest',
                    height=3.3,
                    aspect=1.2)
        .set(xlabel=None,
             ylabel='参与人数',
             title="\n".join(wrap("问题1:如果你坐在全自动驾驶汽车中,以下三个选项中,你更希望车辆选择哪种操作?", 90)))
)

# 隐藏x轴刻度
catp.ax.tick_params(axis='x', bottom=False)
# 调整图例位置,去掉图例标题
catp.legend.set_title('')
sns.move_legend(catp, "upper left", bbox_to_anchor=(1, 1)) # 图例放到图表外侧右侧

plt.tight_layout()
catp.ax.set_yticks((0,10,20,30,40))
for p in catp.ax.patches:
    percentage = '{:.1f}%'.format(100 * p.get_height()/92)
    x = p.get_x() + p.get_width() / 2 - 0.05
    y = p.get_y() + p.get_height() + 0.3
    catp.ax.annotate(percentage, (x, y), size = 12)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:27:00