pandas 绘制多个系列,但只显示一个系列的图例 [英] Pandas plot multiple series but only showing legend for one series

查看:46
本文介绍了 pandas 绘制多个系列,但只显示一个系列的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ipython笔记本(python 2),并在同一图上同时绘制了条形图和折线图.有两个系列(NPS和计数等级).但是,当我尝试显示图例时,它只显示第二个系列的图例.

I'm using an ipython notebook (python 2) and am plotting both a barchart and a line plot on the same plot. There are two series (NPS and Count Ratings). However, when I try to display the legend, it only shows a legend for the second series.

下面是我的代码:

ax=nps_funding_month[35:][nps_funding_month['count_ratings']>=100].set_index('funding_month')['nps_percentage'].\
plot(kind='line',color='green',label='NPS')

plt.ylabel('Net Promoter Score')

ax=nps_funding_month[35:][nps_funding_month['count_ratings']>=100].set_index('funding_month')['count_ratings'].\
plot(kind='bar',secondary_y=True,label='Count of Ratings')

plt.ylabel('Count Ratings')

plt.legend()

plt.title('Net Promoter Score by Funding Month\n(Only Funding Months with at Least 100 Reviews)')

推荐答案

以下代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({"x" : np.arange(5),
                 "a" : np.exp(np.linspace(3,5,5)),
                 "b" : np.exp(-np.linspace(-1,0.5,5)**2)})

ax=df.plot(x="x", y="a", kind='line',color='green',label='NPS')

plt.ylabel('Net Promoter Score')

ax2 = df.plot(x="x", y="b", kind='bar',secondary_y=True,label='Count of Ratings', ax=ax)

plt.ylabel('Count Ratings')

plt.title('Superlongtitle that is not needed')  
plt.show()

产生

请注意,第一个轴是作为第二个 Pandas 图 (ax=ax) 的参数给出的,并且没有通过 pyplot 添加图例(它通过 Pandas 自动出现).

Note that the first axes is given as argument to the second pandas plot (ax=ax) and no legend is added via pyplot (it comes automatically through pandas).

问题可能是图例被条形隐藏了.原因是图例位于第一个(下)轴中.有两种选择.

The problem may then be that the legend is hidden by the bars. The reason for that is that the legend resides in the first (lower) axes. There are two options.

  1. 我们可以将其移至辅助轴,然后更改其位置.

  1. We could move it to the secondary axes and then also change its location.

leg = ax.get_legend()
leg.remove()        # remove it from ax
ax2.add_artist(leg) # add it to ax2
leg._set_loc(4)

其中 loc 4 表示左下角"并且是 放置图例的代码.

Where the the loc 4 means "lower left" and is one of the codes to place the legend.

我们可以将其移出情节,(如如何将图例移出情节)

We can move it out of the plot, (as in How to put the legend out of the plot)

leg._set_loc(2)
leg.set_bbox_to_anchor((1.1,1))
ax.figure.subplots_adjust(right=0.6) # make space for the legend outside

这篇关于 pandas 绘制多个系列,但只显示一个系列的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆