首页 > 解决方案 > Pandas secondary_y:如何将图例放在情节之外?

问题描述

当我在 Pandas 中使用“secondary_y”时,我正在努力移动图例的位置。下面的代码给出了一个例子:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'C' : [4,5,6,7], 'S' : [10,20,30,40],'R' : [100,50,-30,-50]})
fig, ax = plt.subplots()
df[['C', 'S', 'R']].plot.bar(ax=ax, rot=90,  secondary_y= ['S', 'R'])

在此处输入图像描述

当不使用“secondary_y”时,以下工作

handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='lower left', ncol=3,
           bbox_to_anchor=(0.25, -.175))

但是当我使用“secondary_y”时,上面的最后一个代码不起作用。

有人知道如何获得图下方的图例吗?

标签: pandaslegend-properties

解决方案


我在https://stackoverflow.com/a/54091202/8046133找到的以下内容有效

h1, l1 = ax.get_legend_handles_labels()
h2, l2 = ax.right_ax.get_legend_handles_labels()
handles = h1+h2
labels = l1+l2
ax.legend(handles, labels, loc='lower left', ncol=3,
       bbox_to_anchor=(0.25, -.575))

推荐阅读