安装ggp​​lot后,matplotlib出现问题

时间:2018-09-12 19:15:44

标签: python matplotlib anaconda python-ggplot jupyter-lab

昨天,我将ggplot安装到我的anaconda环境中。 当我尝试使用在安装ggp​​lot之前有效的matplotlib图时,出现以下错误。我还从其他内联Jupyter实验室代码中得到了错误。任何帮助将不胜感激。我是新来查看数据的人。如果还有另一个绘图模块,请告知我。

plt.rcParams['figure.dpi'] = 200
plt.rcParams.update({'font.size': 5})

fig, ax1 = plt.subplots()
ax1.set_xlabel('Time')

ax1.set_ylabel('price', color='k')
ax1.plot(df['price'], color='#0072b5', label = 'price')
ax1.tick_params(axis='y', labelcolor='k')
#ax1.tick_params(axis='x',  labelrotation = 90) 

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis#

color = 'tab:cyan'
ax2.set_ylabel('gen', color='k')  # we already handled the x-label with ax1
ax2.plot(df['gen'], color='#e2e3e2', label = 'gen')
ax2.tick_params(axis='y', labelcolor='k')

#ax1.legend(loc=2)
#ax2.legend(loc=1)
fig.legend(loc=1, bbox_to_anchor=(1,1), bbox_transform=ax1.transAxes, prop={'size':5})


fig.tight_layout()  # otherwise the right y-label is slightly clipped
fig.suptitle('%s, %s %s' % (df, month_graph, year_graph) , fontsize=8)
fig.subplots_adjust(top=0.90)
plt.savefig("%s.png" % ('genPrice'))
plt.show()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-032d973b53a3> in <module>()
     19 #ax1.legend(loc=2)
     20 #ax2.legend(loc=1)
---> 21 fig.legend(loc=1, bbox_to_anchor=(1,1), bbox_transform=ax1.transAxes, prop={'size':5})
     22 
     23 

TypeError: legend() missing 2 required positional arguments: 'handles' and 'labels'

2 个答案:

答案 0 :(得分:0)

回溯表明缺少两个“必需”参数,尽管实际上,根据documentation,它们是可选的。如果自安装新模块以来遇到此问题,则可能您已将matplotlib降级为必须使用两个参数的先前版本。在这种情况下,您可能希望从控制台pip install matplotlib --upgrade

答案 1 :(得分:0)

matplotlib.figure.Figure.legend的签名是matplotlib的in version 2.0.2

legend(handles, labels, *args, **kwargs)

in version 2.1.2或以上时

legend(*args, **kwargs)

这意味着您在安装ggp​​lot时已将matplotlib降级。如果要继续使用该较旧的matplotlib版本,则需要自己提供句柄和标签。看起来像

h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()

fig.legend(h1+h2, l1+l2, loc=1, bbox_to_anchor=(1,1), 
           bbox_transform=ax1.transAxes, prop={'size':5})