Python matplotlib获取ylim值
我正在使用Python中的Python matplotlib获取ylim值,python,matplotlib,plot,Python,Matplotlib,Plot,我正在使用Python中的matplotlib来绘制数据(使用plot和errorbar函数)。我必须绘制一组完全独立的绘图,然后调整它们的ylim值,以便可以轻松地进行视觉比较 如何从每个绘图中检索ylim值,以便分别获取较低和较高ylim值的最小值和最大值,并调整绘图,以便对其进行视觉比较 当然,我可以只分析数据,然后得出我自己定制的ylim值。。。但是我想用matplotlib来为我做这件事。有没有关于如何轻松(高效)做到这一点的建议 下面是我的Python函数,它使用matplotlib
matplotlib
来绘制数据(使用plot
和errorbar
函数)。我必须绘制一组完全独立的绘图,然后调整它们的ylim
值,以便可以轻松地进行视觉比较
如何从每个绘图中检索ylim
值,以便分别获取较低和较高ylim值的最小值和最大值,并调整绘图,以便对其进行视觉比较
当然,我可以只分析数据,然后得出我自己定制的ylim
值。。。但是我想用matplotlib
来为我做这件事。有没有关于如何轻松(高效)做到这一点的建议
下面是我的Python函数,它使用matplotlib
进行绘图:
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)
只需使用
轴。get_ylim()
,它与set_ylim
非常相似。从:
get_ylim()
获取y轴范围[底部,顶部]
如果直接使用plt
api,则可以避免调用axes
:
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.ylim([-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)
利用上面的好答案,并假设您只使用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()
上述代码应生成以下输出图。
这是一个老问题,但我没有看到有人提到,根据具体情况,
sharey
选项可能可以为您完成所有这些,而不是挖掘轴限制、边距等。文档中有一个,但是y轴也可以这样做。我使用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())
是否有办法获得图形区域限制,而不是轴限制?黑色边框稍微超出了这些值。@Peterhrlich这只是边距。我发现
plt.gca().get_ylim()
很方便-不需要额外的轴定义。或者,我更喜欢使用fig,ax=plt.subpllots()
然后通过fig
或ax
路由我的所有功能直接使用plt api与使用Axis相比是否有优势?我看到很多人建议使用Axis更好,但我还没有弄清楚原因。Axis更易于编程-例如,您可以构建一个函数库,对Axis对象进行操作。但是plt
对象更适合于快速完成某些事情。因此,如果您正在修补,plt
更快。如果你正在构建一个更大的应用程序,axes可能是最好的。这就是我的经历。老实说,总的来说,这是一个奇怪的API。
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())