[英]Matplotlib set subplot axis size iteratively
有几个相关问题( 此处、 此处和此处),但建议的解决方案在我的情况下不起作用。
我正在迭代地创建子图,所以我不知道每个子图的宽度(它是在调用 plt.subplots() 之后计算的),这意味着我无法在最初设置每个子图的大小创建它们。 我想在创建子图 x 轴后设置它的大小。
想象一下:
items = [A,B,C] #this could have any number of items in it
f,ax = plt.subplots(len(items),1, figsize=(10,10)) #figsize is arbitrary and could be anything
for i in range(len(items)):
#calculate x and y data for current item
#calculate width of x axis for current item
plt.sca(ax[i])
cax = plt.gca()
cax.plot(x,y)
#here is where I would like to set the x axis size
#something like cax.set_xlim(), but for the size, not the limit
注 1:单位无关紧要,但相对大小很重要,因此它可以是以像素或厘米为单位的大小,甚至可以是基于相对宽度计算的比率。
注意 2:在这种情况下,x 轴的宽度与 x 限制无关,因此我不能只设置 x 限制并期望轴正确缩放。
另外,我试图保持这段代码的简短,因为它要与不熟悉 Python 的人共享,所以如果唯一的解决方案涉及添加一堆行,那是不值得的,我将忍受不正确缩放的轴。 这是一种审美偏好,但不是必需的。 谢谢!
您可以创建一个新的GridSpec
指定height_ratios
然后更新每个ax
的位置:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
# create figure
f, ax = plt.subplots(3, 1, figsize=(10,10))
# plot some data
ax[0].plot([1, 2, 3])
ax[1].plot([1, 0, 1])
ax[2].plot([1, 2, 20])
# adjust subplot sizes
gs = GridSpec(3, 1, height_ratios=[5, 2, 1])
for i in range(3):
ax[i].set_position(gs[i].get_position(f))
plt.show()
我之前在这里问过一个类似的问题。 用例略有不同,但它可能仍然有帮助。
当然现在你得到了答案,或者这个问题已被弃用,但如果其他人正在搜索,我使用“Bbox”解决了这个问题。 这个想法是这样的:
from matplotlib.transforms import Bbox
fig, ax = plt.subplots(3,1, figsize = (11,15))
ax[0].set_position(Bbox([[0.125, 0.6579411764705883], [0.745, 0.88]]))
ax[2].set_position(Bbox([[0.125, 0.125], [0.745, 0.34705882352941175]]))
有关更多信息,请查看https://matplotlib.org/api/transformations.html#matplotlib.transforms.Bbox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.