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

如何让Matplotlib柱状图始终显示0%-100%的Y轴范围?

如何让Matplotlib柱状图Y轴始终显示0%到100%范围?

问题描述

我有一段Python代码,用于绘制展示预计算百分比列表的基础柱状图:

def plot_errors_percent_bar_graph(list):
    fig, ax = plt.subplots()
    x_labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
    ax.bar(x_labels, list, color='green')
    ax.set_ylabel('Percentage of Number of Errors')
    ax.set_xlabel('Labels')
    ax.set_title('Total Percentage Number of Errors')
    plt.show(block=False)
    plt.pause(0.001)

当前图表的Y轴仅显示列表中的最高百分比(如下方示例图显示80%):
示例图表
请问如何让图表始终显示0%到100%的Y轴范围,即使列表中没有接近100%的值?

解决方案

直接使用Matplotlib轴对象的set_ylim()方法,强制指定Y轴的范围为0到100即可。修改后的代码如下:

def plot_errors_percent_bar_graph(list):
    fig, ax = plt.subplots()
    x_labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
    ax.bar(x_labels, list, color='green')
    ax.set_ylabel('Percentage of Number of Errors')
    ax.set_xlabel('Labels')
    ax.set_title('Total Percentage Number of Errors')
    # 固定Y轴范围在0到100之间
    ax.set_ylim(0, 100)
    plt.show(block=False)
    plt.pause(0.001)

说明

set_ylim()方法接受两个参数,分别对应Y轴的最小值和最大值。设置为(0, 100)后,不管你的数据中最高百分比是多少,Y轴都会固定显示从0%到100%的完整区间,不会再自动适配数据的最大值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:35:03