I am trying to plot multiple features which have different ranges on two y axis. Each axis might contain more than one feature. Code snippet below includes object "Prin Balances" which is a df which contains datatypes float indexed by dates. "Delinquent States" is a list containing a subset of the column headers of Prin Balances.
Delinquent_States = ['1 Mos','2 Mos','3 Mos','> 3 Mos']
fig, ax = plt.subplots()
plt.plot(Prin_Balances['UPB'], '--r', label='UPB')
plt.legend()
ax.tick_params('Bal', colors='r')
# Get second axis
ax2 = ax.twinx()
plt.plot(Prin_Balances[Delinquent_States], label=Delinquent_States)
plt.legend()
ax.tick_params('vals', colors='b')
My output needs to be cleaned up, esp the legends.
Any suggestions welcomed.
As simple as:
import pandas
import matplotlib.pyplot as plt
import random
# Generate some random data
df = pandas.DataFrame({'a': [random.uniform(0,0.05) for i in range(15)],
'b': [random.uniform(0,0.05) for i in range(15)],
'c': [random.uniform(0.8,1) for i in range(15)],
'd': [random.uniform(0.8, 1) for i in range(15)],
'e': [random.uniform(0.8, 1) for i in range(15)]})
plt.plot(df)
Returns:
I would suggest however plotting them separately:
fig, ax = plt.subplots(nrows=2,ncols=1)
plt.subplot(2,1,1)
plt.plot(df['a'], 'r', label='Line a')
plt.legend()
plt.subplot(2,1,2)
plt.plot(df['b'], 'b', label='Line b')
plt.legend()
Which yelds:
ADDED:
You can set different scales for each side of the plot:
fig, ax = plt.subplots()
plt.plot(df['a'], '--r', label='Line a')
plt.plot(df['b'], '--k', label='Line b')
plt.legend()
ax.tick_params('vals', colors='r')
# Get second axis
ax2 = ax.twinx()
plt.plot(df['c'], '--b', label='Line c')
plt.plot(df['d'], '--g', label='Line d')
plt.plot(df['e'], '--c', label='Line e')
plt.legend()
ax.tick_params('vals', colors='b')
Not the prettiest, but you get the point.