Matplotlib Error: 'str' object has no attribute 'get_figure'
Matplotlib Error: 'str' object has no attribute 'get_figure'
我有如下所示的代码,但在 ltycs.plot(ax='time'):
行中出现我无法理解的错误
#PRODUCE AND VISUALIZE FORECAST
pred_uc = results.get_forecast(steps=12-cm+1) # forecast steps in terms of "y" which is months
pred_ci = pred_uc.conf_int()
import matplotlib.dates as mdates
#from matplotlib.dates import MonthLocator
ax = y['2020':].plot(label='observed', figsize=(14, 7)) #crop of blue or "observed" val in final plot
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
pred_uc.predicted_mean.plot(ax=ax, label='Forecast')
ax.fill_between(pred_ci.index,
pred_ci.iloc[:, 0],
pred_ci.iloc[:, 1], color='k', alpha=.25)
#ax.set_xlabel('Date')
ax.set_ylabel('MOS Wind Speed')
#add the LT monthly average to plot
lty = ylt.groupby(ylt.index.month).mean()
lty = lty.to_frame()
lty.columns=['LT Mean']
ltyc = lty.iloc[0:12].reset_index() # extract curr month to end of LT mean monthly wind speed
#create date sequence using date format of df = y
ltyc['time'] = pd.to_datetime(ltyc["time"], format='%m').apply(lambda,
dt:dt.replace(year=2020))#convert the "Date" col to yyyy-mm-dd
ltycs = pd.Series(ltyc['LT Mean'].values, index=ltyc['time'])#convert to Series for plot
ltycs.plot(label='LT Mean',ax=ax,color='k')#ax='time' plots x months
ltycs.plot(ax='time')
plt.grid(b=True, which='major', color='k', linestyle='-')
plt.grid(b=True, which='minor', color='g', linestyle='-', alpha=0.2)#alpha is the minor grid
plt.minorticks_on()
plt.legend()
plt.show()
变量“ltycs”是一个 pandas 系列,看起来像这样:
ltycs
Out[382]:
time
2020-01-01 7.411365
2020-02-01 7.193070
2020-03-01 7.397183
2020-04-01 7.684527
2020-05-01 7.670577
2020-06-01 7.348572
2020-07-01 6.898480
2020-08-01 6.852384
2020-09-01 7.250651
2020-10-01 7.681693
2020-11-01 7.587329
2020-12-01 7.444730
dtype: float64
我在图中得到了我正在寻找的 x 轴上有几个月的结果,但程序因这个错误而停止 -
File "C:\Users\U321103\AppData\Local\Continuum\anaconda3\envs\Stats\lib\site-
packages\pandas\plotting\_matplotlib\core.py", line 323, in _setup_subplots
fig = self.ax.get_figure()
AttributeError: 'str' object has no attribute 'get_figure'
这是我的绘图,在将 'time' 列或月份分配给 x 轴后,它看起来符合预期。谢谢!
在评论中回答有问题的 ltycs.plot(ax='time')
行的目的后:
正是这一行 ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
完成了您所描述的(即在 x 轴上显示月份)。绘制 pandas.DataFrame、ax
参数需要一个 matplotlib 轴对象,而不是字符串,这就是您收到错误的原因。当您包含有问题的行时获得正确标签的原因是 - 您没有 运行 plt.minorticks_on()
调用。
所以,你应该做的,首先是通过 matplotlib 子图创建一个 matplotlib 轴,然后设置 minorticks_on 然后绘制 pandas.DataFrames,将 matplotlib ax 对象传递给它们各自的绘图功能为:
#PRODUCE AND VISUALIZE FORECAST
pred_uc = results.get_forecast(steps=12-cm+1) # forecast steps in terms of "y" which is months
pred_ci = pred_uc.conf_int()
import matplotlib.dates as mdates
#from matplotlib.dates import MonthLocator
figure, ax = plt.subplots(figsize = (14,7))
plt.minorticks_on()
y['2020':].plot(label='observed', ax = ax)
pred_uc.predicted_mean.plot(ax=ax, label='Forecast')
ax.fill_between(pred_ci.index,
pred_ci.iloc[:, 0],
pred_ci.iloc[:, 1], color='k', alpha=.25)
#ax.set_xlabel('Date')
ax.set_ylabel('MOS Wind Speed')
#add the LT monthly average to plot
lty = ylt.groupby(ylt.index.month).mean()
lty = lty.to_frame()
lty.columns=['LT Mean']
ltyc = lty.iloc[0:12].reset_index() # extract curr month to end of LT mean monthly wind speed
#create date sequence using date format of df = y
ltyc['time'] = pd.to_datetime(ltyc["time"], format='%m').apply(lambda,
dt:dt.replace(year=2020))#convert the "Date" col to yyyy-mm-dd
ltycs = pd.Series(ltyc['LT Mean'].values, index=ltyc['time'])#convert to Series for plot
ltycs.plot(label='LT Mean',ax=ax,color='k')#ax='time' plots x months
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.grid(b=True, which='major', color='k', linestyle='-')
plt.grid(b=True, which='minor', color='g', linestyle='-', alpha=0.2)#alpha is the minor grid
plt.legend()
plt.show()
我有如下所示的代码,但在 ltycs.plot(ax='time'):
行中出现我无法理解的错误#PRODUCE AND VISUALIZE FORECAST
pred_uc = results.get_forecast(steps=12-cm+1) # forecast steps in terms of "y" which is months
pred_ci = pred_uc.conf_int()
import matplotlib.dates as mdates
#from matplotlib.dates import MonthLocator
ax = y['2020':].plot(label='observed', figsize=(14, 7)) #crop of blue or "observed" val in final plot
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
pred_uc.predicted_mean.plot(ax=ax, label='Forecast')
ax.fill_between(pred_ci.index,
pred_ci.iloc[:, 0],
pred_ci.iloc[:, 1], color='k', alpha=.25)
#ax.set_xlabel('Date')
ax.set_ylabel('MOS Wind Speed')
#add the LT monthly average to plot
lty = ylt.groupby(ylt.index.month).mean()
lty = lty.to_frame()
lty.columns=['LT Mean']
ltyc = lty.iloc[0:12].reset_index() # extract curr month to end of LT mean monthly wind speed
#create date sequence using date format of df = y
ltyc['time'] = pd.to_datetime(ltyc["time"], format='%m').apply(lambda,
dt:dt.replace(year=2020))#convert the "Date" col to yyyy-mm-dd
ltycs = pd.Series(ltyc['LT Mean'].values, index=ltyc['time'])#convert to Series for plot
ltycs.plot(label='LT Mean',ax=ax,color='k')#ax='time' plots x months
ltycs.plot(ax='time')
plt.grid(b=True, which='major', color='k', linestyle='-')
plt.grid(b=True, which='minor', color='g', linestyle='-', alpha=0.2)#alpha is the minor grid
plt.minorticks_on()
plt.legend()
plt.show()
变量“ltycs”是一个 pandas 系列,看起来像这样:
ltycs
Out[382]:
time
2020-01-01 7.411365
2020-02-01 7.193070
2020-03-01 7.397183
2020-04-01 7.684527
2020-05-01 7.670577
2020-06-01 7.348572
2020-07-01 6.898480
2020-08-01 6.852384
2020-09-01 7.250651
2020-10-01 7.681693
2020-11-01 7.587329
2020-12-01 7.444730
dtype: float64
我在图中得到了我正在寻找的 x 轴上有几个月的结果,但程序因这个错误而停止 -
File "C:\Users\U321103\AppData\Local\Continuum\anaconda3\envs\Stats\lib\site-
packages\pandas\plotting\_matplotlib\core.py", line 323, in _setup_subplots
fig = self.ax.get_figure()
AttributeError: 'str' object has no attribute 'get_figure'
这是我的绘图,在将 'time' 列或月份分配给 x 轴后,它看起来符合预期。谢谢!
在评论中回答有问题的 ltycs.plot(ax='time')
行的目的后:
正是这一行 ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
完成了您所描述的(即在 x 轴上显示月份)。绘制 pandas.DataFrame、ax
参数需要一个 matplotlib 轴对象,而不是字符串,这就是您收到错误的原因。当您包含有问题的行时获得正确标签的原因是 - 您没有 运行 plt.minorticks_on()
调用。
所以,你应该做的,首先是通过 matplotlib 子图创建一个 matplotlib 轴,然后设置 minorticks_on 然后绘制 pandas.DataFrames,将 matplotlib ax 对象传递给它们各自的绘图功能为:
#PRODUCE AND VISUALIZE FORECAST
pred_uc = results.get_forecast(steps=12-cm+1) # forecast steps in terms of "y" which is months
pred_ci = pred_uc.conf_int()
import matplotlib.dates as mdates
#from matplotlib.dates import MonthLocator
figure, ax = plt.subplots(figsize = (14,7))
plt.minorticks_on()
y['2020':].plot(label='observed', ax = ax)
pred_uc.predicted_mean.plot(ax=ax, label='Forecast')
ax.fill_between(pred_ci.index,
pred_ci.iloc[:, 0],
pred_ci.iloc[:, 1], color='k', alpha=.25)
#ax.set_xlabel('Date')
ax.set_ylabel('MOS Wind Speed')
#add the LT monthly average to plot
lty = ylt.groupby(ylt.index.month).mean()
lty = lty.to_frame()
lty.columns=['LT Mean']
ltyc = lty.iloc[0:12].reset_index() # extract curr month to end of LT mean monthly wind speed
#create date sequence using date format of df = y
ltyc['time'] = pd.to_datetime(ltyc["time"], format='%m').apply(lambda,
dt:dt.replace(year=2020))#convert the "Date" col to yyyy-mm-dd
ltycs = pd.Series(ltyc['LT Mean'].values, index=ltyc['time'])#convert to Series for plot
ltycs.plot(label='LT Mean',ax=ax,color='k')#ax='time' plots x months
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.grid(b=True, which='major', color='k', linestyle='-')
plt.grid(b=True, which='minor', color='g', linestyle='-', alpha=0.2)#alpha is the minor grid
plt.legend()
plt.show()