【问题标题】:Pandas plot multiple series but only showing legend for one series熊猫绘制多个系列,但只显示一个系列的图例
【发布时间】:2018-01-28 08:13:45
【问题描述】:

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

下面是我的代码:

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)')

【问题讨论】:

标签: python pandas matplotlib plot


【解决方案1】:

以下代码

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 自动添加)。

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

  1. 我们可以将它移动到辅助轴,然后也改变它的位置。

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

    位置4 的意思是“左下角”并且是the codes to place the legend 之一。

  2. 我们可以把它移出情节,(如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
    

【讨论】:

  • 太棒了。这在一定程度上有效(图例与其中一个条重叠)。您能否补充一下如何将图例移动到其他地方?非常感谢!
  • 另请注意,此答案中提出的方法仅在两个图使用相同的数据框时才有效。如果使用了两个不同的数据框,请参考this question 的答案。
  • 哇,谢谢。我已经搜索了好几天才能弄清楚这一点。
  • 从 pandas 1.3.3 开始,此示例不再有效。您应该将label 替换为legend
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 2020-03-02
相关资源
最近更新 更多