简体   繁体   English

为 matplotlib 中的所有子图设置相同的轴限制

[英]Setting the same axis limits for all subplots in matplotlib

This problem seems simple enough, but I can't find a pythonic way to solve it.这个问题看起来很简单,但我找不到解决它的pythonic方法。 I have several (four) subplots that are supposed to have the same xlim and ylim .我有几个(四个)子图应该具有相同的xlimylim Iterating over all subplots à la迭代所有子图 à la

f, axarr = plt.subplots(4)
for x in range(n):
    axarr[x].set_xlim(xval1, xval2)
    axarr[x].set_ylim(yval1, yval2)

isn't the nicest way of doing things, especially for 2x2 subplots – which is what I'm actually dealing with.不是最好的做事方式,尤其是对于 2x2 子图——这正是我真正要处理的。 I'm looking for something like plt.all_set_xlim(xval1, xval2) .我正在寻找类似plt.all_set_xlim(xval1, xval2)

Note that I don't want anything else to change (ticks and labels should be controlled separately).请注意,我不想更改任何其他内容(刻度和标签应单独控制)。

EDIT: I'm using the plt.subplots(2, 2) wrapper.编辑:我正在使用plt.subplots(2, 2)包装器。 Following dienzs answer, I tried plt.subplots(2, 2,sharex=True, sharey=True) – almost right, but now the ticks are gone except for the left and bottom row.在 dienzs 回答之后,我尝试了plt.subplots(2, 2,sharex=True, sharey=True) - 几乎是正确的,但现在除了左行和底行之外,刻度线都消失了。

Set the xlim and ylim properties on the Artist object by matplotlib.pyplot.setp() https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.setp.html通过matplotlib.pyplot.setp() https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.setp.html在 Artist 对象上设置xlimylim属性

# Importing matplotlib.pyplot package.
import matplotlib.pyplot as plt

# Assigning 'fig', 'ax' variables.
fig, ax = plt.subplots(2, 2)

# Defining custom 'xlim' and 'ylim' values.
custom_xlim = (0, 100)
custom_ylim = (-100, 100)

# Setting the values for all axes.
plt.setp(ax, xlim=custom_xlim, ylim=custom_ylim)

You can try this.你可以试试这个。

#set same x,y limits for all subplots
fig, ax = plt.subplots(2,3)
for (m,n), subplot in numpy.ndenumerate(ax):
    subplot.set_xlim(xval1,xval2)
    subplot.set_ylim(yval1,yval2)

您可以使用共享轴来共享 x 和/或 y 限制,但允许以任何其他方式自定义轴。

This is not at all elegant, but it worked for me...这一点都不优雅,但它对我有用......

fig, axes = plt.subplots(6, 3, sharex=True)
axes[0, 0].set_xlim(right=10000) # sharex=True propagates it to all plots
for i in range(6):
    for j in range(3):
        axes[i, j].plot('Seconds', df.columns[2+3*i+j], data=df)  # your plot instructions
plt.subplots_adjust(wspace=.5, hspace=0.2)

If you have multiple subplots, ie如果你有多个子图,即

fig, ax = plt.subplots(4, 2)

You can use it.你可以使用它。 It gets limits of y ax from first plot.它从第一个图中获得 y 轴的限制。 If you want other subplot just change index of ax[0,0] .如果您想要其他子图,只需更改ax[0,0]索引。

plt.setp(ax, ylim=ax[0,0].get_ylim())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM