首页 文章

matplotlib得到ylim值

提问于
浏览
68

我正在使用 matplotlib 从Python绘制数据(使用 ploterrorbar 函数) . 我必须绘制一组完全独立且独立的图,然后调整它们的值,以便在视觉上轻松比较 .

如何从每个绘图中检索 ylim 值,以便我可以分别获取下ylim值和上ylim值的最小值和最大值,并调整绘图以便可以直观地比较它们?

当然,我可以只分析数据并提出我自己的自定义 ylim 值...但我想使用 matplotlib 为我做这个 . 关于如何轻松(和有效)地做到这一点的任何建议?

这是我使用 matplotlib 绘制的Python函数:

import matplotlib.pyplot as plt

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    # axes
    axes = plt.gca()
    axes.set_xlim([-0.5, len(values) - 0.5])
    axes.set_xlabel('My x-axis title')
    axes.set_ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

    # close figure
    plt.close(fig)

2 回答

  • 23

    只需使用 axes.get_ylim() ,它与 set_ylim 非常相似 . 来自docs

    get_ylim()获取y轴范围[bottom,top]

  • 91
    ymin, ymax = axes.get_ylim()
    

    如果您正在使用 plt 结构,为什么还要打扰轴?这应该工作:

    def myplotfunction(title, values, errors, plot_file_name):
    
        # plot errorbars
        indices = range(0, len(values))
        fig = plt.figure()
        plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')
    
        plt.xlim([-0.5, len(values) - 0.5])
        plt.xlabel('My x-axis title')
        plt.ylabel('My y-axis title')
    
        # title
        plt.title(title)
    
        # save as file
        plt.savefig(plot_file_name)
    
       # close figure
        plt.close(fig)
    

    或者情况不是这样吗?

相关问题