在 matplotlib 和 seaborn 之间共享 x 轴

耶斯列

我有熊猫数据DataFrame

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

np.random.seed(786)

df = pd.DataFrame({'a':np.arange(0, 1, 0.05),
                   'b':np.random.rand(20) - .5})

print (df)
       a         b
0   0.00  0.256682
1   0.05 -0.192555
2   0.10  0.393919
3   0.15 -0.113310
4   0.20  0.373855
5   0.25 -0.423764
6   0.30 -0.123428
7   0.35 -0.173446
8   0.40  0.440818
9   0.45 -0.016878
10  0.50  0.055467
11  0.55 -0.165294
12  0.60 -0.216684
13  0.65  0.011099
14  0.70  0.059425
15  0.75  0.145865
16  0.80 -0.019171
17  0.85  0.116984
18  0.90 -0.051583
19  0.95 -0.096527

我想绘制barplot并添加垂直线:

plt.figure(figsize=(10,5))
sns.barplot(x = 'a', y = 'b', data = df)
plt.vlines(x = 0.45, ymin = 0, ymax = 0.6, color = 'red', linewidth=5)

没有与ticklabels问题,因为overlaping也行应该在点0.45附近instaed0x axis

波尔特

我尝试了link1link2link3link4 中的许多解决方案但仍然为两个图正确设置了轴。

什么是问题?是否可以在图之间共享 x 轴?

预期输出 - 正确对齐的垂直线并且在 x 轴上也不重叠刻度线:

图片

The x-axis in the barplot is categorical, so it doesn't have the values of your df.a as a real scale, but only as tick labels. You could change e.g. df.a[19] = 2 and nothing will change except the label of the last bar tick.

So categorical axis means the coordinates are 0 for the first bar, 1 for the second and so on ... 19 for the last.

My approach then would be to set the vertical line at xpos * 19/.95:

plt.vlines(x = .45*19/.95, ymin = 0, ymax = 0.6, color = 'red', linewidth=5)

在此处输入图片说明

For the general case you could add a lambda function to calculate the conversion:

f = lambda x: (x-df.a.values[0]) * (df.a.size-1) / (df.a.values[-1] - df.a.values[0])
plt.vlines(x = f(.45), ymin = 0, ymax = 0.6, color = 'red', linewidth=5)

However, as df.a.values is only printed as tick labels, it should go linearly from start to end.

关于 x 轴标记的问题:我只能说它没有出现在我的系统中,除了垂直线之外,上面的绘图代码与您的相同。也许它是在一次又一次尝试 vlines 时引入的。

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章