Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a line to matplotlib subplots

I would like to do a subplot of two figures with matplotlib and add a horizontal line in both. This is probably basic, but I don't know how to specify that one of the lines should be drawn in the first figure, they both end up in the last one. e.g.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.rand(10))

fig, axes = plt.subplots(nrows=2,ncols=1)

f1= s1.plot(ax=axes[0])
l1=plt.axhline(0.5,color='black',ls='--')
l1.set_label('l1')

f2= s1.plot(ax=axes[1])
l2=plt.axhline(0.7,color='red',ls='--') 
l2.set_label('l2')

plt.legend()

subplot with horizontal lines

axhline does not have "ax" as an argument, as the pandas plot function does. So this would work:

l1=plt.axhline(0.5,color='black',ls='--',ax=axes[0])

I read the examples in matplotlib and I tried with this other option that does not work either (probably for good reasons)

axes[0].plt.axhline(0.5,color='black',ls='--')

How should I do to draw lines in subplots? Ideally with a legend Thanks!

like image 528
Nabla Avatar asked Mar 01 '17 14:03

Nabla


1 Answers

with the help of @Nick Becker I answered my own "syntax" question.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline


s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.randn(10))

fig, axes = plt.subplots(nrows=2,ncols=1)

f1= s1.plot(ax=axes[0],label='s1')
l1=axes[0].axhline(0.5,color='black',ls='--')
l1.set_label('l1')

axes[0].legend(loc='best')

f2= s1.plot(ax=axes[1],label='s2')

l2=axes[1].axhline(0.5,color='black',ls='--')

l2.set_label('l2')

axes[1].legend(loc='best')

subplots with horizontal lines

like image 156
Nabla Avatar answered Oct 22 '22 01:10

Nabla