[英]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.