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

Matplotlib绘图中无法设置线条Y轴位置及垂直间距问题

解决Matplotlib多行线条垂直间距调整问题

你的代码核心问题是每个年份的线条组都从同一个y轴起始点(0.1)开始绘制,导致不同年份的线条垂直重叠,且线条间的步长设置未配合整体布局调整。下面是修改后的代码,可实现「缩小线条间距、除最下方一行外其余向下移动」的需求:

import matplotlib.pyplot as plt

surfaces = [['sea ice', 'sea ice'],
            ['sea ice', 'sea ice', 'glacier'],
            ['sea ice', 'sea ice'],
            ['glacier', 'glacier', 'sea ice', 'sea ice']]

# 定义颜色映射
colors = {'sea ice': 'blue', 'glacier': 'red'}

linewidth = 6
# 给每个年份分配独立的垂直基准位置,整体向下偏移(起始值从0.05开始)
year_base_ys = [0.05, 0.12, 0.19, 0.26]  # 基准间距可按需调整
line_gap = 0.015  # 缩小线条间的垂直间距

fig, ax = plt.subplots(figsize=(10, 4))

for year_idx, surface_list in enumerate(surfaces):
    year = 2020 + year_idx
    y_offset = year_base_ys[year_idx]  # 每个年份用独立的基准y值
    for surface in surface_list:
        # 绘制水平线条
        ax.plot([year - 0.4, year + 0.4], [y_offset, y_offset], 
                color=colors[surface], linewidth=linewidth)
        y_offset += line_gap  # 线条间的小间距

ax.set_xlabel('年份')
ax.set_ylabel('种群')
ax.set_xticks([2020, 2021, 2022, 2023])
ax.set_xticklabels(['2020/21', '2021/22', '2022/23', '2023/24'])
ax.set_yticks([])
# 可选:调整y轴范围,避免线条被画布边缘裁剪
ax.set_ylim(0, 0.35)

plt.show()

关键改动说明:

  • 年份独立基准y值:用year_base_ys给每个年份的线条组分配不同垂直起始位置,既避免重叠,又通过降低整体起始值(从0.05开始)实现「除最下方外其余向下移动」的效果
  • 缩小线条间距:把线条间的步长从0.02调整为0.015,可根据视觉需求继续调小(比如0.01)
  • y轴范围控制:添加ax.set_ylim确保所有线条都完整显示在画布内,不会被顶部或底部边缘裁剪

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 01:44:51