python - Matplotlib 迭代设置子图轴大小
问题描述
有几个相关的问题(here、here和here),但建议的解决方案不适用于我的情况。
我正在迭代地创建子图,所以我不提前知道每个子图的宽度(在调用 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 的人共享的,所以如果唯一的解决方案涉及添加一堆行,那是不值得的,我会忍受不正确缩放的轴。这是一种审美偏好,但不是要求。谢谢!
解决方案
现在你肯定得到了答案,或者这个问题已被弃用,但如果其他人正在搜索,我使用“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
推荐阅读
- javascript - 使用 Webpack 编译 js 文件时出现“未捕获的类型错误”
- c++ - 为什么我可以通过原始指针而不是 shared_ptr 来修改对象?
- java - 我在预期的 Android Studio .class 标识符中有代码错误,我该如何解决?
- sql - 解决 Vertica [Vertica][VJDBC](4160) 和 [Vertica][VJDBC](4680) 中的查询错误
- windows - windows上的python多处理似乎脱离了venv
- javascript - Cors 阻止客户端访问本地 vertx-server
- perl - 使用动态参数将命令添加到 visudo
- node.js - 根据属性值查找div内容
- r - 从 GAM 预测 R 中分组数据帧的值
- html - PDF 未在对象标签内显示