Pandas bar plot with specific colors and legend location?

五迷三道 提交于 2019-12-02 18:01:11

If you want to add the legend manually, you have to ask the subplot for the elements of the bar plot:

In [17]: ax = x.plot(kind='bar', legend=False)

In [18]: patches, labels = ax.get_legend_handles_labels()

In [19]: ax.legend(patches, labels, loc='best')
Out[19]: <matplotlib.legend.Legend at 0x10b292ad0>

Also, plt.legend(loc='best') or ax.legend(loc='best') should "just work", because there are already "links" to the bar plot patches set up when the plot is made, so you don't have to pass a list of axis labels.

I'm not sure if the version of pandas you're using returns a handle to the subplot (ax = ...) but I'm fairly certain that 0.7.3 does. You can always get a reference to it with plt.gca().

The most succinct way to go is:

x.plot(kind="bar").legend(bbox_to_anchor=(1.2, 0.5))

or in general

x.plot(kind="bar").legend(*args, **kwargs)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!