Search code examples
pythonmatplotlibseaborn

Is there a way to add lines across subplots in Python


I have a simple plot, to which I've added lines as below:

mid = d[d.Position==0].Price.mean()
b_a = d[(d.Position==0) & (d.Side == 0)].Price.values
b_b = d[(d.Position==0) & (d.Side == 1)].Price.values

f, ax = plt.subplots()
sns.set_color_codes('muted')

sns.barplot(data = d[d.Side==0], x = 'Price', y = 'Size', color = 'b',  native_scale=True)
sns.barplot(data = d[d.Side==1], x = 'Price', y = 'Size', color = 'r',  native_scale=True)

ax.xaxis.set_major_locator(ticker.MultipleLocator(.0001))
plt.axvline(x=mid, color = 'b', lw = 1.5)
plt.axvline(x=b_a, color = 'k', lw = 1, ls='--')
plt.axvline(x=b_b, color = 'k', lw = 1, ls='--')

enter image description here

Data looks like this: d

    Position    Operation   Side    Price   Size
9   9   0   1   0.7289  -16
8   8   0   1   0.729   -427
7   7   0   1   0.7291  -267
6   6   0   1   0.7292  -15
5   5   0   1   0.7293  -16
4   4   0   1   0.7294  -16
3   3   0   1   0.7295  -426
2   2   0   1   0.7296  -8
1   1   0   1   0.7297  -14
0   0   0   1   0.7298  -37
10  0   0   0   0.7299  6
11  1   0   0   0.73    34
12  2   0   0   0.7301  7
13  3   0   0   0.7302  9
14  4   0   0   0.7303  16
15  5   0   0   0.7304  15
16  6   0   0   0.7305  429
17  7   0   0   0.7306  16
18  8   0   0   0.7307  265
19  9   0   0   0.7308  18

I'd like to plot a number of this sequentially using matplotlib's subplots method like this (here, x and y are just a collection of values from prior d dataframes assembled for plotting):

cnt = 5

f, ax = plt.subplots(cnt, 1, sharex=True)
sns.set_color_codes('muted')

for i in range(cnt):
    sns.barplot(x = x.iloc[i, 10:].values, y = y.iloc[i, 10:].values, color = 'b',  native_scale=True, ax = ax[i])
    sns.barplot(x = x.iloc[i, :10].values, y = y.iloc[i, 10:].values, color = 'r',  native_scale=True, ax = ax[i])
    ax[i].xaxis.set_major_locator(ticker.MultipleLocator(.0001))
    

enter image description here

Is there a way to create connecting lines across subplots? Like this crude version below?

enter image description here


Solution

  • This is a bit hacky but it should work:

    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.figure(1).clf()
    fig, ax = plt.subplots(5, 1, num=1, sharex=True)
    
    # plot your data
    x = np.arange(100)
    for a in ax:
        plt.sca(a)
        plt.plot(x, np.random.randn(100))
    
    # add the lines
    values = [20, 20, 30, 30, 20]
    for i in range(5):
        plt.sca(ax[i])
        ylim = plt.ylim()
        v = values[i]
        v_ = v if i==0 else values[i-1]
        plt.plot([v, v_], ylim, 'g')
        plt.plot([v-10, v_-10], ylim, 'r--')
        plt.plot([v+10, v_+10], ylim, 'r--')
        plt.ylim(*ylim)
    
    plt.tight_layout()
    plt.subplots_adjust(hspace=0)
    
    plt.show()
    

    enter image description here