如何在 panda MultiIndex Dataframe 中绘制 ylabel

How to plot ylabel in panda MultiIndex Dataframe

我需要从列的 0 级绘制带有 ylabels 的 MultiIndex 数据框。数据框如下:

PCs                                pc1           pc2           pc3  \
explained_variance_ratio  9.977643e-01  2.196399e-03  3.275875e-05   
wavelength                                                           
540.00                        0.015110     -0.004772     -0.018467   
540.05                        0.015110     -0.004772     -0.018467   
540.10                        0.015110     -0.004772     -0.018467   
540.15                        0.015110     -0.004772     -0.018467   
540.20                        0.015110     -0.004772     -0.018467   
540.25                        0.015110     -0.004772     -0.018467   
540.30                        0.015110     -0.004772     -0.018467   
540.35                        0.015110     -0.004772     -0.018467   
540.40                        0.015081     -0.004226     -0.017577   
540.45                        0.015081     -0.004226     -0.017577  
.......

ylabel 应该是 pc1、pc2、pc3.... 波长是 xlabel。

我试过以下方法都不行:

pca_df.plot(subplots=True, sharex=True, title='Principle Components', \
    legend=False, y=list(pca_df.columns.levels[0]))

错误是:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 1716, in plot_frame
    ser = frame[y]
  File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1652, in __getitem__
    return self._getitem_array(key)
  File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1697, in _getitem_array
    return self.take(indexer, axis=1, convert=True)
  File "/usr/lib/python2.7/dist-packages/pandas/core/generic.py", line 1166, in take
    indices, len(self._get_axis(axis)))
  File "/usr/lib/python2.7/dist-packages/pandas/core/indexing.py", line 1438, in _maybe_convert_indices
    if mask.any():
AttributeError: 'bool' object has no attribute 'any'

也尝试过:

pca_df.plot(subplots=True, sharex=True, title='Principle Components', \
    legend=False)
plt.ylabel(pca_df.columns.levels[0])

虽然它绘制了覆盖所有图的 ylabel 只是:

Index([u'pc1', u'pc10', u'pc2', u'pc3', u'pc4', u'pc5', u'pc6', u'pc7', u'pc8', u'pc9'], dtype='object')

我通常在调用 plot 后对轴本身进行大部分格式化。 试试这个:

axes = pca_df.plot(subplots=True, sharex=True, title='Principle Components', legend=False)
for ax, label in zip(axes.ravel(), pca_df.columns.levels[0]):
     ax.set_ylabel(label)

我发现使用轴 API 比尝试将其全部放入 plot 方法调用要容易得多。请注意,当 subplots 为 True 时,绘图方法 returns 一个轴数组,您必须像我在此处所做的那样通过索引或迭代访问它。 .ravel 是处理二维数组的好方法,当你的图形有多个行和列时,你会得到这种方法,但如果数组只是一维的,它仍然有效。