Matplotlib:如何在 2 个独立的轴上显示条形图和线条的图例?
Matplotlib: how to show legend for bar chart and line on 2 separate axes?
我在左轴上绘制条形图,在右轴上绘制折线图。如何在同一个图例框中显示两者的图例?
使用下面的代码,我得到了两个单独的图例框;另外,我需要手动指定第二个图例的位置,经过大量的反复试验,否则它会与第一个重叠。
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() return 两个不同的对象无法连接。
python 错误的好处在于,它们通常可以从字面上理解并直接告诉您问题所在。
"TypeError" 告诉你类型有问题。您可以打印类型:
print(type(l1)) # <class 'matplotlib.container.BarContainer'>
print(type(l2)) # <type 'list'>
现在,"can only concatenate tuple (not "list") to tuple" 告诉您不能将条形容器添加到列表中。
简单的解决方案:添加两个列表:
myl=[l1]+l2
我在左轴上绘制条形图,在右轴上绘制折线图。如何在同一个图例框中显示两者的图例?
使用下面的代码,我得到了两个单独的图例框;另外,我需要手动指定第二个图例的位置,经过大量的反复试验,否则它会与第一个重叠。
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() return 两个不同的对象无法连接。
python 错误的好处在于,它们通常可以从字面上理解并直接告诉您问题所在。
"TypeError" 告诉你类型有问题。您可以打印类型:
print(type(l1)) # <class 'matplotlib.container.BarContainer'>
print(type(l2)) # <type 'list'>
现在,"can only concatenate tuple (not "list") to tuple" 告诉您不能将条形容器添加到列表中。
简单的解决方案:添加两个列表:
myl=[l1]+l2