简体   繁体   English

在 matplotlib 子图中共享 Y 轴

[英]Sharing Y-axis in a matplotlib subplots

I have been trying to create a matplotlib subplot (1 x 3) with horizontal bar plots on either side of a lineplot .我一直在尝试创建一个matplotlib subplot (1 x 3)在 lineplot 的任一侧都有水平条形图

It looks like this:它看起来像这样: 在此处输入图像描述

The code for generating the above plot -生成上述 plot 的code -

u_list = [2, 0, 0, 0, 1, 5, 0, 4, 0, 0]
n_list = [0, 0, 1, 0, 4, 3, 1, 1, 0, 6]
arr_ = list(np.arange(10, 11, 0.1))

data_ = pd.DataFrame({
    'points': list(np.arange(0, 10, 1)),
    'value': [10.4, 10.5, 10.3, 10.7, 10.9, 10.5, 10.6, 10.3, 10.2, 10.4][::-1]
})

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 8))

ax1 = plt.subplot(1, 3, 1)
sns.barplot(u_list, arr_, orient="h", ax=ax1)

ax2 = plt.subplot(1, 3, 2)
x = data_['points'].tolist()
y = data_['value'].tolist()
ax2.plot(x, y)
ax2.set_yticks(arr_)
plt.gca().invert_yaxis()

ax3 = plt.subplot(1, 3, 3, sharey=ax1, sharex=ax1)
sns.barplot(n_list, arr_, orient="h", ax=ax3)

fig.tight_layout()
plt.show()

Edit编辑

How do I share the y-axis of the central line plot with the other horizontal bar plots?如何与其他horizontal bar共享central line ploty-axis

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.我会将所有 y 轴的限制设置为相同的范围,设置所有轴的刻度,然后将除最左侧轴之外的所有轴的刻度/刻度标签设置为空。 Here is what I mean:这就是我的意思:

from matplotlib import pyplot as plt
import numpy as np

u_list = [2, 0, 0, 0, 1, 5, 0, 4, 0, 0]
n_list = [0, 0, 1, 0, 4, 3, 1, 1, 0, 6]
arr_ = list(np.arange(10, 11, 0.1))
x = list(np.arange(0, 10, 1))
y = [10.4, 10.5, 10.3, 10.7, 10.9, 10.5, 10.6, 10.3, 10.2, 10.4]

fig, axs = plt.subplots(1, 3, figsize=(20, 8))

axs[0].barh(arr_,u_list,height=0.1)
axs[0].invert_yaxis()

axs[1].plot(x, y)
axs[1].invert_yaxis()

axs[2].barh(arr_,n_list,height=0.1)
axs[2].invert_yaxis()


for i in range(1,len(axs)):
    axs[i].set_ylim( axs[0].get_ylim() ) # align axes
    axs[i].set_yticks([]) # set ticks to be empty (no ticks, no tick-labels)

fig.tight_layout()
plt.show()

在此处输入图像描述

This is a minimal example and for the sake of conciseness, I refrained from mixing matplotlib and searborn.这是一个最小的例子,为了简洁起见,我没有混合 matplotlib 和 searborn。 Since seaborn uses matplotlib under the hood, you can reproduce the same output there (but with nicer bars).由于 seaborn 在引擎盖下使用 matplotlib,因此您可以在那里重现相同的 output(但条形更好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM