I have been trying to create a matplotlib subplot (1 x 3)
with horizontal bar plots on either side of a lineplot.
The code
for generating the above plot –
JavaScript
x
27
27
1
u_list = [2, 0, 0, 0, 1, 5, 0, 4, 0, 0]
2
n_list = [0, 0, 1, 0, 4, 3, 1, 1, 0, 6]
3
arr_ = list(np.arange(10, 11, 0.1))
4
5
data_ = pd.DataFrame({
6
'points': list(np.arange(0, 10, 1)),
7
'value': [10.4, 10.5, 10.3, 10.7, 10.9, 10.5, 10.6, 10.3, 10.2, 10.4][::-1]
8
})
9
10
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 8))
11
12
ax1 = plt.subplot(1, 3, 1)
13
sns.barplot(u_list, arr_, orient="h", ax=ax1)
14
15
ax2 = plt.subplot(1, 3, 2)
16
x = data_['points'].tolist()
17
y = data_['value'].tolist()
18
ax2.plot(x, y)
19
ax2.set_yticks(arr_)
20
plt.gca().invert_yaxis()
21
22
ax3 = plt.subplot(1, 3, 3, sharey=ax1, sharex=ax1)
23
sns.barplot(n_list, arr_, orient="h", ax=ax3)
24
25
fig.tight_layout()
26
plt.show()
27
Edit
How do I share the
y-axis
of thecentral line plot
with the otherhorizontal bar
plots?
Advertisement
Answer
I would set the limits of all y-axes to the same range, set the ticks in all axes and than set the ticks/tick-labels of all but the most left axis to be empty. Here is what I mean:
JavaScript
1
28
28
1
from matplotlib import pyplot as plt
2
import numpy as np
3
4
u_list = [2, 0, 0, 0, 1, 5, 0, 4, 0, 0]
5
n_list = [0, 0, 1, 0, 4, 3, 1, 1, 0, 6]
6
arr_ = list(np.arange(10, 11, 0.1))
7
x = list(np.arange(0, 10, 1))
8
y = [10.4, 10.5, 10.3, 10.7, 10.9, 10.5, 10.6, 10.3, 10.2, 10.4]
9
10
fig, axs = plt.subplots(1, 3, figsize=(20, 8))
11
12
axs[0].barh(arr_,u_list,height=0.1)
13
axs[0].invert_yaxis()
14
15
axs[1].plot(x, y)
16
axs[1].invert_yaxis()
17
18
axs[2].barh(arr_,n_list,height=0.1)
19
axs[2].invert_yaxis()
20
21
22
for i in range(1,len(axs)):
23
axs[i].set_ylim( axs[0].get_ylim() ) # align axes
24
axs[i].set_yticks([]) # set ticks to be empty (no ticks, no tick-labels)
25
26
fig.tight_layout()
27
plt.show()
28
This is a minimal example and for the sake of conciseness, I refrained from mixing matplotlib and searborn. Since seaborn uses matplotlib under the hood, you can reproduce the same output there (but with nicer bars).