I am trying to plot a data on 2 y-axis by using twinx().
The issue is that the legend on the axis – twinx() is not getting displayed.
the code used for expected result is as below:
df_plot = DF02.query('Make == "Acura"')
Fig = plt.figure()
ax1 = Fig.add_axes([0, 0, 1, 1])
ax2 = ax1.twinx()
# Drawing a line plot
sns.lineplot(data = df_plot,
x = 'Year',
y = 'highway MPG',
hue = 'Model',
palette = 'rocket',
style = 'Model',
markers = True,
dashes = False,
ax = ax1)
# Drawing line plot on ax2 using matplotlib
ax2.plot(df_plot['Year'],
df_plot['avg highway MPG'],
marker = '*',
label = 'avg highway MPG')
# Set x-axis and y-axis ticks
xticks = np.arange(1990, 2021, 2)
ax1.set_xticks(xticks)
yticks = np.arange(10, 41, 2)
ax1.set_yticks(yticks)
ax2.set_yticks(yticks)
ax2.axes.get_yaxis().set_visible(False)
# Change name of plot title
ax1.set_title("Line Plot in Seaborn", fontdict = {'weight': 'bold'})
# Change x and y axis titles
ax1.set_xlabel('Year')
ax1.set_ylabel('Highway Fuel Economy [MPG]')
# Placing the legend
ax1.legend(title = "Vehicle Modeln", loc = 'center right', bbox_to_anchor = (1.3, 0.5))
ax2.legend(title = 'Legend', loc = 'upper right', bbox_to_anchor = (1, 1))
# Enabling the grid
ax1.grid(ls = '--', color = 'lightgrey')
However when plotted using seaborn, the legend does not appear as expected.
Code used in actual result is as below:
df_plot = DF02.query('Make == "Acura"')
Fig = plt.figure()
ax1 = Fig.add_axes([0, 0, 1, 1])
ax2 = ax1.twinx()
# Drawing a line plot
sns.lineplot(data = df_plot,
x = 'Year',
y = 'highway MPG',
hue = 'Model',
palette = 'rocket',
style = 'Model',
markers = True,
dashes = False,
ax = ax1)
sns.lineplot(data = df_plot,
x = 'Year',
y = 'avg highway MPG',
ax = ax2)
# Set x-axis and y-axis ticks
xticks = np.arange(1990, 2021, 2)
ax1.set_xticks(xticks)
yticks = np.arange(10, 41, 2)
ax1.set_yticks(yticks)
ax2.set_yticks(yticks)
ax2.axes.get_yaxis().set_visible(False)
# Change name of plot title
ax1.set_title("Line Plot in Seaborn", fontdict = {'weight': 'bold'})
# Change x and y axis titles
ax1.set_xlabel('Year')
ax1.set_ylabel('Highway Fuel Economy [MPG]')
# Placing the legend
ax1.legend(title = "Vehicle Modeln", loc = 'center right', bbox_to_anchor = (1.3, 0.5))
ax2.legend(loc = 'upper right', bbox_to_anchor = (1, 1))
# Enabling the grid
ax1.grid(ls = '--', color = 'lightgrey')
Can anyone please suggest how to get the result similar to expected result by using seaborn on both axes ax1 and ax2?