Plotting a horizontal line on multiple subplots in python using pyplot

0 Answers

Add horizontal lines to plot based on sort_values criteria

You can use faster DataFrame.nlargest for top 5 rows and then iterrows with axhline:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

df = pd.read_csv('for_stack_nums')
#print (df.head())

top_5 = df[['High','Low','# of Trades']].nlargest(5, '# of Trades')
print (top_5)
      High     Low  # of Trades
94  164.88  164.84          470
90  164.90  164.86          465
93  164.90  164.86          431
89  164.87  164.83          427
65  164.60  164.56          332

axnum = df[['High','Low']].plot()

for idx, l in top_5.iterrows():
    plt.axhline(y=l['High'], color='r')
    plt.axhline(y=l['Low'], color='b')

Also subset is not necessary:

df = pd.read_csv('for_stack_nums.csv')
#print (df.head())

axnum = df[['High','Low']].plot()

for idx, l in df.nlargest(5, '# of Trades').iterrows():
    plt.axhline(y=l['High'], color='r')
    plt.axhline(y=l['Low'], color='b')

I am plotting three subplots on the same page. I want to draw a horiZontal line through all the subplots. Following is my code and the resultant graph: (You can notice I can get the horizontal line on one of the plots, but not all)

gs1 = gridspec.GridSpec(8, 2)
gs1.update(left=0.12, right=.94, wspace=0.12)
ax1 = plt.subplot(gs1[0:2, :])
ax2 = plt.subplot(gs1[3:5, :], sharey=ax1)
ax3 = plt.subplot(gs1[6:8, :], sharey=ax1)

ax1.scatter(theta_cord, density, c = 'r', marker= '1')
ax2.scatter(phi_cord, density, c = 'r', marker= '1')
ax3.scatter(r_cord, density, c = 'r', marker= '1')
ax1.set_xlabel('Theta (radians)')
ax1.set_ylabel('Galaxy count')
ax2.set_xlabel('Phi (radians)')
ax2.set_ylabel('Galaxy count')
ax3.set_xlabel('Distance (Mpc)')
ax3.set_ylabel('Galaxy count')
loc = plticker.MultipleLocator(base=0.001)

plt.axhline(y=0.002, xmin=0, xmax=1, hold=None)

This generates the following:

Again, I want the line I drew on the last subplot to appear on the first two subplots too. How do I do that?