我编写了以下代码,以在不同的子图中绘制6个饼图,但出现错误。如果我仅使用它绘制2个图表,则此代码可以正常工作,但除此以外的其他任何地方都会产生错误。
我的数据集中有6个类别变量,其名称存储在list中cat_cols
。图表应从训练数据中绘制train
。
码
fig, axes = plt.subplots(2, 3, figsize=(24, 10))
for i, c in enumerate(cat_cols):
train[c].value_counts()[::-1].plot(kind = 'pie', ax=axes[i], title=c, autopct='%.0f', fontsize=18)
axes[i].set_ylabel('')
plt.tight_layout()
错误
AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'
我们该如何纠正?
plt.subplots(2, 3, figsize=(24, 10))
创建两组3个子图,而不是一组6个子图。array([[<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>],
[<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>]], dtype=object)
axes
使用axes.ravel()
。
numpy.ravel
,它返回一个展平的数组。axe = [sub for x in axes for sub in x]
axe
。import pandas as pd
import numpy as np
# sinusoidal sample data
sample_length = range(1, 6+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])
# crate the figure and axes
fig, axes = plt.subplots(2, 3, figsize=(24, 10))
# unpack all the axes subplots
axe = axes.ravel()
# assign the plot to each subplot in axe
for i, c in enumerate(df.columns):
df[c].plot(ax=axe[i])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句