使用Matplotlib优化此绘制图表的脚本



我想绘制一个数据帧,该数据帧中有41列,因此有41个图表要绘制。我写了一个剧本,但加载太慢了。是否有优化此脚本的解决方案?是否可以使用循环函数来简化zip函数中的列表?

import matplotlib.pyplot as plt
import pandas as pd
fig,((axs),(axs2),(axs3),(axs4),(axs5),(axs6),(axs7),(axs8),(axs9)) = plt.subplots(9,5,figsize=(15,6))
for ax, y in zip(axs,['XPEV','M','MLCO','VIPS','HD']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)

for ax, y in zip(axs2,['LVS','PTON','SBUX','BLMN','NCLH']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)

for ax, y in zip(axs3,['NIO','NKE','NKLA','NLS','QS']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)

for ax, y in zip(axs4,['AYRO','RMO','TSLA','XL','ASO']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)

for ax, y in zip(axs5,['TOL','VSTO','BABA','FTCH','RIDE']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)
for ax, y in zip(axs6,['EBAY','DS','DKNG','DHI','UAA']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)

for ax, y in zip(axs7,['VFC','TPX','ARVL','GM','GOEV']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)

for ax, y in zip(axs8,['PLBY','CCL','GME','CVNA','LOTZ']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)

for ax, y in zip(axs9,['F']):
ax.plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax.ticklabel_format(style='plain', axis='y')
ax.set_title(y)

plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
plt.show()
  • 没有样本数据,所以我模拟了它
  • 首先将plt.subplots()返回的轴列表简化为1D
  • 迭代级别1索引中的股票代码
  • 具有上述步骤的简单plot()
  • tight_layout()为我过度压缩,因此已发表评论
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
tickers_data = pd.DataFrame({("Volume",t):np.random.randint(20,200, 7) for t in ['XPEV','M','MLCO','VIPS','HD']+['LVS','PTON','SBUX','BLMN','NCLH']+['NIO','NKE','NKLA','NLS','QS']+['AYRO','RMO','TSLA','XL','ASO']+['TOL','VSTO','BABA','FTCH','RIDE']+['EBAY','DS','DKNG','DHI','UAA']+
['VFC','TPX','ARVL','GM','GOEV']+['PLBY','CCL','GME','CVNA','LOTZ']+['F']}, index=pd.date_range("1-Jan-2021", periods=7))
tickers_data
fig,ax = plt.subplots(9,5,figsize=(15,6))
ax = np.array(ax).flatten()
for i,y in enumerate(tickers_data.columns.get_level_values(1)):
ax[i].plot(tickers_data.index.strftime("%d"),tickers_data['Volume',y])
ax[i].ticklabel_format(style='plain', axis='y')
ax[i].set_title(y)

# plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
plt.show()

最新更新