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

Python绘图:如何将yticks垂直下移0.2厘米?

解决Seaborn条形图中yticks垂直下移0.2厘米的问题

要精准把yticks向下移动0.2厘米,可以用Matplotlib的坐标变换工具,直接基于厘米单位调整刻度位置,不受图表尺寸影响。

修改后的完整代码

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.transforms import ScaledTranslation

VAL = [8, 4, 5, 20]
objects = ['h', 'b', 'c', 'a']
y_pos = np.arange(len(objects))

cmap = plt.get_cmap('RdYlGn_r')
norm = plt.Normalize(vmin=min(VAL), vmax=max(VAL))
ax = sns.barplot(x=VAL, y=objects, hue=VAL, palette='RdYlGn_r', dodge=False)

# 拿到所有y轴刻度标签对象
yticks = ax.get_yticklabels()
# 定义偏移:0.2厘米向下,转成Matplotlib用的英寸单位(1英寸=2.54厘米)
offset = ScaledTranslation(0, -0.2/2.54, ax.figure.dpi_scale_trans)

# 给每个刻度标签加上偏移变换
for tick in yticks:
    tick.set_transform(tick.get_transform() + offset)

plt.show()

关键说明

  • ScaledTranslation会根据图表的DPI自动换算厘米到绘图坐标的偏移,保证在不同分辨率下偏移量都是准确的0.2厘米。
  • 负号代表向下偏移,如果要向上移动,改成正数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:25:27