原文链接:http://www.juzicode.com/archives/3273
错误提示:
利用pandas绘制多个子图时报错:AttributeError: ‘list’ object has no attribute ‘get_figure’
#juzicode.com #vx:桔子code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rc('font',family='Youyuan',size='11')
plt.rc('axes',unicode_minus='False')
t = np.arange(0, 10, 0.1) #100行,用作index
s = np.random.randn(100,5) #100行5列的随机数据
df = pd.DataFrame(s, index=t,columns=['A1','B2','C3','D4','E4'])
df = df.cumsum() #累加
fig,axes=plt.subplots(3,3,figsize=(10,10))
group = [axes[0][0], axes[0][2], axes[1][1], axes[2][0], axes[2][2]]
df.plot(title='随机曲线 by桔子code', ax=group)
plt.show()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-29-5b24a5692d3e> in <module>
13 fig,axes=plt.subplots(3,3,figsize=(10,10))
14 group = [axes[0][0], axes[0][2], axes[1][1], axes[2][0], axes[2][2]]
---> 15 df.plot(title='随机曲线 by桔子code', ax=group)
16 plt.show()
d:\python\python38\lib\site-packages\pandas\plotting\_core.py in __call__(self, *args, **kwargs)
947 data.columns = label_name
948
--> 949 return plot_backend.plot(data, kind=kind, **kwargs)
950
951 __call__.__doc__ = __doc__
d:\python\python38\lib\site-packages\pandas\plotting\_matplotlib\__init__.py in plot(data, kind, **kwargs)
59 kwargs["ax"] = getattr(ax, "left_ax", ax)
60 plot_obj = PLOT_CLASSES[kind](data, **kwargs)
---> 61 plot_obj.generate()
62 plot_obj.draw()
63 return plot_obj.result
d:\python\python38\lib\site-packages\pandas\plotting\_matplotlib\core.py in generate(self)
268 self._args_adjust()
269 self._compute_plot_data()
--> 270 self._setup_subplots()
271 self._make_plot()
272 self._add_table()
d:\python\python38\lib\site-packages\pandas\plotting\_matplotlib\core.py in _setup_subplots(self)
329 axes = fig.add_subplot(111)
330 else:
--> 331 fig = self.ax.get_figure()
332 if self.figsize is not None:
333 fig.set_size_inches(self.figsize)
AttributeError: 'list' object has no attribute 'get_figure'
错误原因:
1、pandas DataFrame实例的plot()方法绘制多个子图时,没有传入subplots入参。
解决方法:
1、在plot()方法中传入subplots=True:df.plot(title=’随机曲线 by桔子code’, subplots=True, ax=group) 。
#juzicode.com #vx:桔子code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rc('font',family='Youyuan',size='11')
plt.rc('axes',unicode_minus='False')
t = np.arange(0, 10, 0.1) #100行,用作index
s = np.random.randn(100,5) #100行5列的随机数据
df = pd.DataFrame(s, index=t,columns=['A1','B2','C3','D4','E4'])
df = df.cumsum() #累加
fig,axes=plt.subplots(3,3,figsize=(10,10))
group = [axes[0][0], axes[0][2], axes[1][1], axes[2][0], axes[2][2]]
df.plot(title='随机曲线 by桔子code', subplots=True, ax=group)
plt.show()
扩展内容:
关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识