Home > Back-end >  how to add secondary y-axis with plt.plot_date()
how to add secondary y-axis with plt.plot_date()

Time:08-05

Im trying to plot date in x-axis, sales volume in primary y-axis and price in secondary y-axis. Since x-axis is a date type, I have used plt.plot_date() function from matplotlib. I tried secondary_y = True which throws

AttributeError: 'Line2D' object has no property 'secondary_y'

Is it possible to add secondary y-axis with plt.plot_date() or any better way to do this?

Code as below:

plt.plot_date(x = df['Date'], y = df['Sales_Volume'], fmt = '-')
plt.plot_date(x = df['Date'], y = df['Price'], fmt = '-', secondary_y = True)
plt.xticks(rotation = 90)
plt.show()

Please note: sales volume and price has different ranges

CodePudding user response:

you need to use twinx() to add a secondary axis to your plot. I have created a simple example to show the same. I have added a few options so that you can see how to add color, legend, etc. Use the ones you want/like.

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import matplotlib.dates as mdates
from matplotlib.dates import AutoDateFormatter, AutoDateLocator

date_today = datetime.now()
days = pd.date_range(date_today, date_today   timedelta(20), freq='D') 
np.random.seed(seed=1111)
df = pd.DataFrame({'date': days}) # Your date field
df = df.set_index('date')

fig,ax1 = plt.subplots(figsize=(12,5))
l1, = ax1.plot(df.index,np.random.rand(len(df),1)*100, marker = "o", color='green') #Your Price field
ax1.set_ylabel('Price (y1 axis)')
ax2 = ax1.twinx() ##Using twinx to make ax2 as secondary axis for ax1
l2, = ax2.plot(df.index,np.random.rand(len(df),1)*800,marker = "o", color='red') #Your sales field
ax2.set_ylabel('Sales-volume (y2 axis)')

fig.legend([l1, l2], ["Price", "Sales Volume"])

xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)

ax1.xaxis.set_major_locator(xtick_locator)
ax1.xaxis.set_major_formatter(xtick_formatter)

enter image description here

  • Related