首页 > 解决方案 > ax.twinx 标签出现两次

问题描述

我一直在尝试使用 Matplotlib 和 Seaborn 制作基于 excel 的图表。代码来自互联网,适合我想要的。问题是图例出现了 2 次。你有什么建议?

报告截图:在此处输入图片描述

Excel表格为:

    Month     Value (tsd eur)  Total MAE

0  Mar 2020            14.0      1714.0
1  Apr 2020             22.5     1736.5
2  Jun 2020            198.0     1934.5
3  Jan 2021             45.0     1979.5
4  Feb 2021             60.0     2039.5
5  Jan 2022             67.0     2106.5
6  Feb 2022            230.0     2336.5
7  Mar 2022            500.0     2836.5

代码是:

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

%matplotlib inline

mae=pd.read_excel('Book1.xlsx')
mae['Month'] = mae['Month'].apply(lambda x: pd.Timestamp(x).strftime('%b %Y'))
a=mae['Value (tsd eur)']
b=mae['Total MAE']
#Create combo chart
fig, ax1 = plt.subplots(figsize=(20,12))
color = 'tab:green'
#bar plot creation
ax1.set_title('MAE Investments', fontsize=25)
ax1.set_xlabel('Month', fontsize=23)
ax1.set_ylabel('Investments (tsd. eur)', fontsize=23)
ax1 = sns.barplot(x='Month', y='Value (tsd eur)', data = mae, palette='Blues',label="Value (tsd eur)")
ax1.tick_params(axis='y',labelsize=20)
ax1.tick_params(axis='x', which='major', labelsize=20, labelrotation=40)

#specify we want to share the same x-axis
ax2 = ax1.twinx()

color = 'tab:red'
#line plot creation
ax2.set_ylabel('Total MAE Value', fontsize=16)
ax2 = sns.lineplot(x='Month', y='Total MAE', data = mae, sort=False, color='blue',label="Total MAE")
ax2.tick_params(axis='y', color=color,labelsize=20)

h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, loc=2, prop={'size': 24})

for i,j in b.items():
    ax2.annotate(str(j), xy=(i, j+30))
for i,j in a.items():
    ax1.annotate(str(j), xy=(i, j+2))
#show plot
print(mae)
plt.show()

标签: pandasmatplotlibseabornlegendtwinx

解决方案


更新:在这里找到答案:

带有 twinx() 的辅助轴:如何添加到图例中?

使用的代码:

    lines, labels =ax1.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    ax2.legend(lines + lines2, labels + labels2, title="Legend", loc=2, prop={'size': 24})

代替:

for i,j in b.items():
    ax2.annotate(str(j), xy=(i, j+30))
for i,j in a.items():
    ax1.annotate(str(j), xy=(i, j+2))

推荐阅读