
[英]how to resize figures within a subplot using matplotlib
我试图在子图中调整两个数字的大小。 基本上,我想要一个温度分布为111且压力分布为211的子图。但是,我希望压力值小于温度值。 这有可能没有相当复杂的gridspec lib吗? 我有以下代码: 看看我如何尝试更改每个子图中的figsize。 这是错误的方式吗? 好的,所以 ...
[英]Dynamic subplot using Figures in Matplotlib
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
我想使用 matplotlib 和 pysimplegui 创建一个子图,每次我 select 一些信号复选框(值列表)我应该得到一个对应的 plot 它会根据我的选择动态增加或减小大小所以当我 select 一个复选框相应的 plot 将被绘制并等间距,当我取消选择 plot 时,它应该消失,其他图应该自动占据空间编程语言 - Python3 Matplotlib - 3.6.2
我的要求:
下面的代码满足了我的大部分要求,但只是轴不相互共享,而且每个地块的大小也不同
reff1 : 在创建轴后更改 matplotlib 子图大小/位置reff2 : 在 matplotlib 中动态添加/创建子图
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
number_of_plots = 2
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
gs = gridspec.GridSpec(number_of_plots + 1, 1)
plot_space = gs[0:number_of_plots].get_position(fig)
print(plot_space,
[plot_space.x0, plot_space.y0, plot_space.width, plot_space.height])
ax.set_position(plot_space)
ax.set_subplotspec(gs[0:number_of_plots]) # only necessary if using tight_layout()
fig.tight_layout() # not strictly part of the question
ax = fig.add_subplot(gs[2], sharex=ax)
plt.show()
这是交互部分的基础。
我在每次新选择时从图中删除所有轴,并将新选择的轴添加到相关的GridSpec
上。
由于@lru_cache
,每次都不会重新绘制静止轴。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from functools import lru_cache
plt.ion()
def main():
# Data that will be selected
datas = {
"data1": np.random.randn(100),
"data2": np.random.randn(100),
"data3": np.random.randn(100),
"data4": np.random.randn(100),
}
# Emulate data selection over time
states = (
["data1"],
["data1", "data3"],
["data2", "data3"],
["data1", "data2", "data3"],
["data2"],
)
fig = plt.figure(figsize=(6, 8))
# Create a new ax on fig with corresponding data plotted
@lru_cache
def get_data_ax(data_id):
ax = fig.add_subplot()
ax.plot(datas[data_id])
ax.set_title(data_id)
return ax
# Emulate data selection over time
for data_state in states:
# Remove all axes, add relevant ones later
for ax in fig.axes:
fig.delaxes(ax)
# Create a GridSpec for the axes to be plot
num_plots = len(data_state)
# but give it at least 2 rows so a single ax will not be stretched
num_rows = max(2, num_plots)
gs = GridSpec(num_rows, 1)
# Get all axes to be plotted
# (thanks to @lru_cache, axes are computed only once)
axes = [get_data_ax(data_id) for data_id in data_state]
# Add each ax one by one
for ax_idx, ax in enumerate(axes):
# Choose the right location for the given ax
ax.set_subplotspec(gs[ax_idx])
fig.add_subplot(ax)
plt.pause(2)
if __name__ == "__main__":
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.