我需要从列的0级绘制带有y标签的MultiIndex数据。Dataframe如下:
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
.......标签应该是pc1,pc2,pc3.用x标签的波长。
我试过以下几种方法不起作用:
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])尽管它标出了所有情节,但覆盖所有情节的y标签很简单:
Index([u'pc1', u'pc10', u'pc2', u'pc3', u'pc4', u'pc5', u'pc6', u'pc7', u'pc8', u'pc9'], dtype='object')发布于 2015-05-28 19:43:21
通常,在调用plot之后,我会对ax或axes本身执行大部分格式设置。试试这个:
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)我发现使用axes要容易得多,而不是试图将其全部应用到绘图方法调用中。注意,当子图为True时,绘图方法返回一个轴数组,您必须像这里所做的那样,通过索引或迭代来访问这些轴。当图形有多个行和列时,.ravel是处理二维数组的一种很好的方法,但是如果数组只是一维的话,它仍然可以工作。
https://stackoverflow.com/questions/30509476
复制相似问题