我有基于子圖的大型圖形要使用 matplotlib 在 python 中生成。該圖總共有超過 500 個單獨的地塊,每個地塊都有 1000 個資料點。這可以使用基于for回圈的方法繪制,該方法以下面給出的最小示例為模型
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# define main plot names and subplot names
mains = ['A','B','C','D']
subs = list(range(9))
# generate mimic data in pd dataframe
col = [letter str(number) for letter in mains for number in subs]
col.insert(0,'Time')
df = pd.DataFrame(columns=col)
for title in df.columns:
df[title] = [i for i in range(100)]
# although alphabet and mains are the same in this minimal example this may not always be true
alphabet = ['A', 'B', 'C', 'D']
column_names = [column for column in df.columns if column != 'Time']
# define figure size and main gridshape
fig = plt.figure(figsize=(15, 15))
outer = gridspec.GridSpec(2, 2, wspace=0.2, hspace=0.2)
for i, letter in enumerate(alphabet):
# define inner grid size and shape
inner = gridspec.GridSpecFromSubplotSpec(3, 3,
subplot_spec=outer[i], wspace=0.1, hspace=0.1)
# select only columns with correct letter
plot_array = [col for col in column_names if col.startswith(letter)]
# set title for each letter plot
ax = plt.Subplot(fig, outer[i])
ax.set_title(f'Letter {letter}')
ax.axis('off')
fig.add_subplot(ax)
# create each subplot
for j, col in enumerate(plot_array):
ax = plt.Subplot(fig, inner[j])
X = df['Time']
Y = df[col]
# plot waveform
ax.plot(X, Y)
# hide all axis ticks
ax.axis('off')
# set y_axis limits so all plots share same y_axis
ax.set_ylim(df[column_names].min().min(),df[column_names].max().max())
fig.add_subplot(ax)
然而,這很慢,需要幾分鐘來繪制圖形。是否有更有效(可能for無回圈)的方法來實作相同的結果
uj5u.com熱心網友回復:
回圈的問題不是繪圖,而是用df[column_names].min().min()和設定軸限制df[column_names].max().max()。
df使用 6 個主圖、64 個子圖和 375,000 個資料點進行測驗,當通過搜索每個回圈的最小值和最大值來設定軸限制時,示例的繪圖部分大約需要 360 秒才能完成。但是,通過在回圈之外移動對 min 和 max 的搜索。例如
# set y_lims
y_upper = df[column_names].max().max()
y_lower = df[column_names].min().min()
和改變
ax.set_ylim(df[column_names].min().min(),df[column_names].max().max())
至
ax.set_ylim(y_lower,y_upper)
繪圖時間減少到大約 24 秒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/486715.html
標籤:Python 表现 循环 matplotlib 阴谋
