为 matplotlib 中的所有子图设置相同的轴限制 [英] Setting the same axis limits for all subplots in matplotlib
问题描述
这个问题似乎很简单,但是我找不到解决该问题的Python方法.我有几个(四个)子图,它们应该具有相同的 xlim
和 ylim
.遍历所有子图la
This problem seems simple enough, but I can't find a pythonic way to solve it. I have several (four) subplots that are supposed to have the same xlim
and ylim
. Iterating over all subplots à la
f, axarr = plt.subplots(4)
for x in range(n):
axarr[x].set_xlim(xval1, xval2)
axarr[x].set_ylim(yval1, yval2)
并不是最好的做事方式,尤其是对于2x2的子图–这是我实际上要处理的事情.我正在寻找类似 plt.all_set_xlim(xval1, xval2)
的东西.
isn't the nicest way of doing things, especially for 2x2 subplots – which is what I'm actually dealing with. I'm looking for something like plt.all_set_xlim(xval1, xval2)
.
请注意,我不想更改任何其他内容(刻度和标签应单独控制).
Note that I don't want anything else to change (ticks and labels should be controlled separately).
我正在使用 plt.subplots(2,2)
包装器.遵循dienzs的答案后,我尝试了 plt.subplots(2,2,sharex = True,sharey = True)
–几乎是对的,但是现在除了左侧和底部的行以外,所有的刻度都消失了.
I'm using the plt.subplots(2, 2)
wrapper. 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.
推荐答案
通过 matplotlib.pyplot.setp 在 Artist 对象上设置
https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.setp.html xlim
和 ylim
属性()
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
# 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)
这篇关于为 matplotlib 中的所有子图设置相同的轴限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!