pandas 库不仅因为支持强大的数据分析,还因为它方便的预制绘图方法而变得流行。 有趣的是,pandas 绘图方法实际上只是对现有 matplotlib 调用的方便包装。
也就是说,pandas 的 Series 和 DataFrame 上的 plot() 方法是 plt.plot() 的包装器。 例如,提供的一种便利是,如果 DataFrame 的索引由日期组成,pandas 会在内部调用 gcf().autofmt_xdate() 以获取当前图形并很好地自动格式化 x 轴。
反过来,请记住 plt.plot()(基于状态的方法)隐式地知道当前的 Figure 和当前的 Axes,因此 pandas 通过扩展遵循基于状态的方法。
我们可以通过一些内省来证明这个函数调用的“链”。 首先,让我们构建一个普通的pandas Series,假设我们从一个新的解释器会话开始:
>>> import pandas as pd
>>> s = pd.Series(np.arange(5), index=list('abcde'))
>>> ax = s.plot()
>>> type(ax)
<matplotlib.axes._subplots.AxesSubplot at 0x121083eb8>
>>> id(plt.gca()) == id(ax)
True
这种内部架构有助于了解何时将 Pandas 绘图方法与传统的 matplotlib 调用混合使用,这在下面绘制广受关注的金融时间序列的移动平均线时完成。 ma 是一个pandas Series,我们可以调用ma.plot()(pandas 方法),然后通过检索由此调用创建的Axes(plt.gca())进行自定义,供matplotlib 参考:
>>> import pandas as pd
>>> import matplotlib.transforms as mtransforms
>>> url = 'https://fred.stlouisfed.org/graph/fredgraph.csv?id=VIXCLS'
>>> vix = pd.read_csv(url, index_col=0, parse_dates=True, na_values='.',
... infer_datetime_format=True,
... squeeze=True).dropna()
>>> ma = vix.rolling('90d').mean()
>>> state = pd.cut(ma, bins=[-np.inf, 14, 18, 24, np.inf],
... labels=range(4))
>>> cmap = plt.get_cmap('RdYlGn_r')
>>> ma.plot(color='black', linewidth=1.5, marker='', figsize=(8, 4),
... label='VIX 90d MA')
>>> ax = plt.gca() # Get the current Axes that ma.plot() references
>>> ax.set_xlabel('')
>>> ax.set_ylabel('90d moving average: CBOE VIX')
>>> ax.set_title('Volatility Regime State')
>>> ax.grid(False)
>>> ax.legend(loc='upper center')
>>> ax.set_xlim(xmin=ma.index[0], xmax=ma.index[-1])
>>> trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)
>>> for i, color in enumerate(cmap([0.2, 0.4, 0.6, 0.8])):
... ax.fill_between(ma.index, 0, 1, where=state==i,
... facecolor=color, transform=trans)
>>> ax.axhline(vix.mean(), linestyle='dashed', color='xkcd:dark grey',
... alpha=0.6, label='Full-period mean', marker='')

1)ma 是 VIX 指数的 90 天移动平均线,衡量近期股那个票波动的市场预期。 状态是将移动平均线划分为不同的状态状态。 高 VIX 被视为表明市场恐惧程度加剧。
2)cmap 是一个 ColorMap——一个 matplotlib 对象,它本质上是一个浮点数到 RGBA 颜色的映射。 任何颜色图都可以通过附加“_r”来反转,因此“RdYlGn_r”是反转的红黄绿颜色图。 Matplotlib 在其文档中维护了一个方便的 ColorMaps 视觉参考指南。
3)我们在这里进行的唯一真正的pandas调用是 ma.plot()。 这会在内部调用 plt.plot(),因此为了集成面向对象的方法,我们需要使用 ax = plt.gca() 获得对当前 Axes 的显式引用。
4)第二段代码创建与每个状态箱对应的颜色填充块。 cmap([0.2, 0.4, 0.6, 0.8]) 说,“给我们一个 RGBA 序列,用于沿着 ColorMaps 光谱的第 20、40、60 和 80 个‘百分位数’的颜色。” 使用 enumerate() 是因为我们想将每个 RGBA 颜色映射回一个状态。
Pandas 还内置了一些更高级的情节(这些情节可以单独占用整个教程)。 然而,所有这些,就像它们更简单的对应物一样,在内部依赖于 matplotlib 机制。
更多文章请关注《万象专栏》
转载请注明出处:https://www.wanxiangsucai.com/read/cv11537