matplotlib得到ylim值

时间:2014-09-30 23:05:30

标签: python matplotlib plot

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

如何从每个图中检索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)

5 个答案:

答案 0 :(得分:107)

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

  

get_ylim()

     

获取y轴范围[bottom,top]

答案 1 :(得分:28)

 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)

或者情况不是这样吗?

答案 2 :(得分:3)

利用上面的好答案,并假设您仅使用

中的plt
import matplotlib.pyplot as plt

然后,您可以使用plt.axis()来获得所有四个图解限制,如下例所示。

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8]  # fake data
y = [1, 2, 3, 4, 3, 2, 5, 6]

plt.plot(x, y, 'k')

xmin, xmax, ymin, ymax = plt.axis()

s = 'xmin = ' + str(round(xmin, 2)) + ', ' + \
    'xmax = ' + str(xmax) + '\n' + \
    'ymin = ' + str(ymin) + ', ' + \
    'ymax = ' + str(ymax) + ' '

plt.annotate(s, (1, 5))

plt.show()

上面的代码应产生以下输出图。 enter image description here

答案 3 :(得分:0)

这是一个古老的问题,但是我看不到有提到,根据具体情况,sharey选项可以为您完成所有这些操作,而不是挖掘轴限制,边距等。文档中有一个demo,显示了如何使用sharex,但是使用 y -axes也可以做到这一点。

答案 4 :(得分:0)

我使用ax而不是plt来组合上述方法

import numpy as np
import matplotlib.pyplot as plt

x = range(100)
y = x

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.plot(x, y);

# method 1
print(ax.get_xlim())
print(ax.get_xlim())
# method 2
print(ax.axis())

enter image description here