首页 > 解决方案 > 具有时间序列数据的子图

问题描述

早晨!我正在尝试创建两个子图(1 行和 2 列)。但是我遇到了一些问题。

import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure(figsize=(25,10))
ax1 = fig.add
data.Loc2.resample('W').mean().rolling(window=3).mean().plot()
plt.title("Mean weekly windspeed at Loc2")


data.Loc2.resample('M').mean().rolling(window=4).mean().plot()
plt.title("Mean monthly windspeed at Loc2")

以上是我所拥有的,但它正在创建一个单图,其中两条线沿 x 轴带有“日期”。尝试使用 fig.add_subplot() 或 plt.subplot() 后,数据框的“日期”列出现错误。

import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure(figsize=(25,10))
axOne = plt.subplot(1,2,1)
y = data.Loc2.resample('W').mean().rolling(window=3).mean()
x = data.Date
data.plot(ax = axOne, x = x, y = y, fontsize = 20, c = "blue")
plt.title("Mean weekly windspeed at Loc2")


data.Loc2.resample('M').mean().rolling(window=4).mean().plot()
plt.title("Mean monthly windspeed at Loc2")

这是我尝试任何方法创建子图时遇到的错误。

AttributeError:“DataFrame”对象没有属性“Date”

标签: pythonpandasmatplotlib

解决方案


我建议使用 matplotlib 的面向对象的 API。这就是我要做的:

fig, axes = plt.subplots(ncols=2, figsize=(25,10))
data.Loc2.resample('W').mean().rolling(window=3).mean().plot(ax=axes[0])
axes[0].set_title("Mean weekly windspeed at Loc2")

data.Loc2.resample('M').mean().rolling(window=4).mean().plot(ax=axes[1])
axes[1].set_title("Mean monthly windspeed at Loc2")

推荐阅读