Search code examples
pandasmatplotlibseabornlegendtwinx

ax.twinx label appears twice


I have been trying to make a chart based on an excel, using Matplotlib and Seaborn. Code is from the internet, adapted to what I want. The issue is that the legend appears 2 times. Do you have any recommendations?

Report screenshot: enter image description here

Excel table is:

    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

Code is:

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

Solution

  • Update: found the answer here:

    Secondary axis with twinx(): how to add to legend?

    code used:

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

    insteaf of:

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