Python Matplotlib:为多个时间序列生成子地块
我有以下通过我正在构建的模拟随机生成的数据集: 出于调试目的,我希望能够以一系列小倍数查看这些数据。像这样: 我正试图使用matplotlib和pandas来实现这一点。以下是我的代码:Python Matplotlib:为多个时间序列生成子地块,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有以下通过我正在构建的模拟随机生成的数据集: 出于调试目的,我希望能够以一系列小倍数查看这些数据。像这样: 我正试图使用matplotlib和pandas来实现这一点。以下是我的代码: import pandas as pd import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages def graph_file(f: str): """
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
def graph_file(f: str):
"""
Graphs a single file of data
and exports it as a pdf of separate charts.
"""
data = pd.read_csv(f)
header = data.columns
fname = f[:-4] + '.pdf'
with PdfPages(fname) as pdf:
n = len(header)
time: str = header[0]
# Multiple charts on one page
fig = plt.figure()
for i in range(1, n):
y: str = header[i]
ax = fig.add_subplot()
data.plot(x=time, y=y)
pdf.savefig(bbox_inches='tight')
当我打开.csv
文件并尝试使用Jupyter笔记本运行该功能时,我一次又一次地收到相同的弃用警告:
<ipython-input-5-0563709f3c08>:24: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
ax = fig.add_subplot()
:24:MatplotLibDeprecation警告:使用与先前轴相同的参数添加轴当前将重用先前的实例。在将来的版本中,将始终创建并返回一个新实例。同时,通过向每个轴实例传递唯一的标签,可以抑制此警告,并确保将来的行为。
ax=图添加_子批次()
生成的pdf文件不包含包含包含多个图形的单个页面(这是我希望在第一幅图像中看到的),而是包含单个图形的单个页面:
我到底做错了什么?我非常感谢您提供的任何反馈。这里有一个可以满足您需求的解决方案。它将csv文件读入数据框,并遍历数据框的列以绘制相应的子图
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
def graph_file(f: str):
df = pd.read_csv(f)
fig, axs = plt.subplots(nrows=3, ncols=3)
fig.set_size_inches(20, 10)
fig.subplots_adjust(wspace=0.5)
fig.subplots_adjust(hspace=0.5)
fname = f[:-4] + '.pdf'
with PdfPages(fname) as pdf:
for col, ax in zip(df.columns[1:], axs.flatten()):
ax.plot(df['time (days)'], df[col])
ax.set(xlabel='time (days)', ylabel=col)
ax.tick_params(axis='x', labelrotation=30)
pdf.savefig(bbox_inches='tight')
plt.show()
这太完美了!非常感谢你。