Seaborn子图 - 在线和条形图之间共享x轴

问题描述 投票:0回答:2

我正试图在Juyter实验室笔记本中通过Seaborn创建2个堆叠图表;其中一个是折线图,另一个是条形图。两者都应该共享相同的x轴。

%matplotlib widget

dt = pd.DataFrame.from_dict({'column_x': range(-10,10), 'vals_1': range(10,30), 'vals_2':range(30,50)})

f, axarr = plt.subplots(2, sharex=True)
sns.lineplot(x="column_x", y="vals_1", data=dt, marker="o", ax=axarr[0])
sns.barplot(x="column_x", y="vals_2", data=dt, ax=axarr[1])

问题是 - 这似乎并没有真正共享轴。我不完全确定为什么,我最好的选择是条形图将其x轴视为分类或类似。

Example - wrong axis

有没有办法在两个图之间正确分享(数值)x轴?

谢谢

python matplotlib seaborn
2个回答
1
投票

你是对的,seaborn在制作条形图时将x值视为分类:

来自docs

此函数始终将其中一个变量视为分类,并在相关轴上的序数位置(0,1,... n)处绘制数据,即使数据具有数字或日期类型也是如此。

所以,我认为最简单的方法可能是关闭sharex,并推出自己的:

axarr[0].set_xlim(dt['column_x'].min()-0.5, dt['column_x'].max()+0.5)
axarr[0].xaxis.set_major_locator(ticker.MultipleLocator(1))

应该使两个轴范围和刻度位置看起来相同

enter image description here


2
投票

lineplot是一个数字图,而barplot是一个绝对的情节。你可能想用lineplot替换pointplot,这也是一个绝对的情节。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns


dt = pd.DataFrame.from_dict({'column_x': range(-10,10), 'vals_1': range(10,30), 'vals_2':range(30,50)})

f, axarr = plt.subplots(2, sharex=True)
sns.pointplot(x="column_x", y="vals_1", data=dt, marker="o", ax=axarr[0])
sns.barplot(x="column_x", y="vals_2", data=dt, ax=axarr[1])

plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.