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

2024-10-01 19:24:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在画一个柱状图在左轴和一个折线图在右轴。如何在同一个图例框中显示两者的图例?在

使用下面的代码,我得到了两个单独的图例框;另外,我需要手动指定第二个图例的位置,需要反复试验,否则它将与第一个图例重叠。在

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

如果我在两个不同的轴上有两条线,而不是条形图和折线图,我会:

^{pr2}$

但这在我的案子里行不通。我得到:

myl=l1+l2
TypeError: can only concatenate tuple (not "list") to tuple

我想这一定是因为bar()和plot()返回了两个无法连接的不同对象。在


Tags: importl1dfindexmatplotlibaslinebar
1条回答
网友
1楼 · 发布于 2024-10-01 19:24:05

关于python错误的好处是,它们通常可以直接从字面上理解并告诉您问题所在。在

“TypeError”表示您的类型有问题。您可以打印以下类型:

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

现在,“canoncatenatedtuple(而不是”list“)to tuple”告诉您不能将barcontainer添加到列表中。在

简单解决方案:添加两个列表:

^{pr2}$

相关问题 更多 >

    热门问题