Python中

时间:2015-11-24 03:25:16

标签: python matplotlib seaborn

我正在尝试使用plt.errorbar将错误栏添加到seaborn中的pointplot

import matplotlib
import matplotlib.pylab as plt
import seaborn as sns
import pandas
sns.set_style("white")

data = pandas.DataFrame({"x": [0.158, 0.209, 0.31, 0.4, 0.519],
                        "y": [0.13, 0.109, 0.129, 0.250, 1.10],
                        "s": [0.01]*5})

plt.figure()
sns.pointplot(x="x", y="y", data=data)
plt.errorbar(data["x"], data["y"], yerr=data["s"])
plt.show()
然而,即使绘制了相同的数据,这两个图看起来完全不同。是什么解释了这个以及如何将错误栏添加到点图中?

1 个答案:

答案 0 :(得分:3)

似乎sns.pointplot只使用[0...n-1]数组作为x值,然后使用您提供的x值来标记x轴上的刻度。您可以查看ax.get_xlim()输出[-0.5, 4.5]来查看该内容。 因此,当您向plt.plot提供实际x值时,它们似乎处于错误的位置。

我不会说这是一个错误,因为seaborn认为pointplot的输入是分类的(这里是documentation以获取更多信息)

您可以通过模仿seaborn的行为来解决这个问题:

import matplotlib
import matplotlib.pylab as plt
import seaborn as sns
import pandas
import numpy as np
sns.set_style("white")

data = pandas.DataFrame({"x": [0.158, 0.209, 0.31, 0.4, 0.519],
                        "y": [0.13, 0.109, 0.129, 0.250, 1.10],
                        "s": [0.05]*5})

plt.figure()
sns.pointplot(x="x", y="y", data=data)
plt.errorbar(np.arange(5), data["y"], yerr=data["s"], color='r')
plt.show()

enter image description here