Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting mulitple lines on two y axis using Matplotlib

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.

enter image description here

Any suggestions welcomed.

like image 825
GPB Avatar asked Jul 18 '17 00:07

GPB


People also ask

How do I plot multiple Y-axis in matplotlib?

The easiest way to create a Matplotlib plot with two y axes is to use the twinx() function.

How do I plot multiple Y values in matplotlib?

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.

How do I plot multiple lines in python matplotlib?

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.


1 Answers

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:

Plots

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:

enter image description here

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.

enter image description here

like image 56
Carlo Mazzaferro Avatar answered Oct 06 '22 00:10

Carlo Mazzaferro