在 matplotlib 子图中共享 Y 轴

什哈尔米什拉

我一直在尝试在 lineplot 的两侧创建一个matplotlib subplot (1 x 3)带有水平条形图的图

它看起来像这样: 在此处输入图片说明

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()

编辑

如何共享y-axiscentral line plot与其他horizontal bar地块?

最大限度

我会将所有 y 轴的限制设置为相同的范围,在所有轴上设置刻度,然后将除最左侧轴以外的所有轴的刻度/刻度标签设置为空。这就是我的意思:

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()

在此处输入图片说明

这是一个最小的例子,为了简洁起见,我没有混合使用 matplotlib 和 searborn。由于 seaborn 在底层使用 matplotlib,您可以在那里重现相同的输出(但有更好的条形)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章