3 Upvotes

Add Secondary Axis to Matplotlib Plot

Python
Visualisation & EDA

Here we add a secondary axis to a plot for the ax2 object.

#Secondary Axis
#https://matplotlib.org/gallery/api/two_scales.html

fig, ax = plt.subplots(figsize=(12,7)) 

#Plot net sales value by week data on ax
ax.plot(sales_by_week['Week'], sales_by_week['Net_Sale_Value'], label='Net Sales', color='blue')

#Create second axes object ax2 and set to share the x axis with ax object
ax2 = ax.twinx() 

#Plot profit by week on second object
ax2.plot(sales_by_week['Week'], sales_by_week['Profit'], label='Profit', color='red')

#Label axes
ax.set_xlabel('Week')
ax.set_ylabel('Net Sales')
ax2.set_ylabel('Profit') #Label secondary axis

plt.show()
{{ snippet.title}

By analyseup - Last Updated Jan. 12, 2022, 12:27 a.m.

Did you find this snippet useful?

Sign up to bookmark this in your snippet library

COMMENTS
RELATED SNIPPETS
2
Top Contributors
103
100