我正在左轴上绘制一个条形图,右轴上绘制一个线形图。如何在同一个图例框中显示两个图例?
使用下面的代码,我得到了两个单独的图例框;另外,我需要手动指定第二个图例的位置,并进行大量试错,否则它会重叠在第一个上。
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()返回了两个不同的对象,不能直接拼接在一起。