这个问题看起来很简单,但我无法找到解决它的pythonic方法.我有几个(四个)子图,应该有相同的xlim和ylim.迭代所有子图
f, axarr = plt.subplots(4)
for x in range(n):
axarr[x].set_xlim(xval1, xval2)
axarr[x].set_ylim(yval1, yval2)
Run Code Online (Sandbox Code Playgroud)
这不是最好的做事方式,特别是对于2x2子图 - 这就是我实际处理的内容.我正在寻找类似的东西plt.all_set_xlim(xval1, xval2).
请注意,我不希望任何其他更改(刻度和标签应单独控制).
编辑:我正在使用plt.subplots(2, 2)包装器.在dienzs回答之后,我尝试了plt.subplots(2, 2,sharex=True, sharey=True)- 几乎是正确的,但现在除了左下排之外,蜱已经消失了.
小智 33
通过https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.setp.html在 Artist 对象上设置xlim和ylim属性matplotlib.pyplot.setp()
# 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)
Run Code Online (Sandbox Code Playgroud)
小智 8
你可以试试这个。
#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)
Run Code Online (Sandbox Code Playgroud)
如果你有多个子图,即
fig, ax = plt.subplots(4, 2)
Run Code Online (Sandbox Code Playgroud)
你可以使用它。它从第一个图中获取 y 轴的限制。如果您想要其他子图,只需更改 的索引ax[0,0]。
plt.setp(ax, ylim=ax[0,0].get_ylim())
Run Code Online (Sandbox Code Playgroud)