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.
The easiest way to create a Matplotlib plot with two y axes is to use the twinx() function.
MatPlotLib with Python To make a scatter plot with multiple Y values for each X, we can create x and y data points using numpy, zip and iterate them together to create the scatter plot.
You can plot multiple lines from the data provided by an array in python using matplotlib. You can do it by specifying different columns of the array as the x and y-axis parameters in the matplotlib. pyplot. plot() function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With