Matplotlib:如何在两个独立的轴上显示条形图和线条的图例?

3

我正在左轴上绘制一个条形图,右轴上绘制一个线形图。如何在同一个图例框中显示两个图例?

使用下面的代码,我得到了两个单独的图例框;另外,我需要手动指定第二个图例的位置,并进行大量试错,否则它会重叠在第一个上。

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

df=pd.DataFrame()
df["bar"]=[40,35,50,45]
df["line"]=[.5,.3,.2,.6]

fig,ax=plt.subplots(2)

l1 = ax[0].bar(df.index, df["bar"], label='my bar chart (left axis)', color='royalblue', width = 0.55)
ax0b=ax[0].twinx()
l2 = ax0b.plot(df.index,  df['line'], label='my line (right axis)',color='tomato',marker='.', ls='dashed')

ax[0].legend(loc='upper left', fancybox=True, title='My title')
ax0b.legend(bbox_to_anchor=(0.155,0.8), loc=1)    
plt.show()

如果我有两条不同轴上的线,而不是柱状图和折线图,我会这样做:
myl=l1+l2
labs=[l.get_label() for l in myl]
ax[0].legend(myl, labs, loc='upper left')

但是在我的情况下,这不起作用。我得到了:
myl=l1+l2
TypeError: can only concatenate tuple (not "list") to tuple

我想这是因为bar()和plot()返回了两个不同的对象,不能直接拼接在一起。
2个回答

4

Python错误的好处在于它们通常可以被直接解读,直接告诉您问题所在。

"TypeError" 告诉您存在类型问题。您可以打印类型:

print(type(l1)) # <class 'matplotlib.container.BarContainer'>
print(type(l2)) # <type 'list'>

现在,“can only concatenate tuple (not "list") to tuple”告诉您不能将barcontainer添加到列表中。
简单解决方案:添加两个列表:
myl=[l1]+l2

0
这对我有用: ax - 用于柱状图的坐标轴/子图, ax1 - 用于折线图
handles1, labels1 = ax.get_legend_handles_labels()
handles2, labels2 = ax1.get_legend_handles_labels()
ax.legend((*handles1, *handles2), (labels1, labels2))

请您正确地格式化您的回答。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接