Python 中 matplotlib 和 seaborn 之间的不一致图 [英] inconsistent plot between matplotlib and seaborn in Python

查看:35
本文介绍了Python 中 matplotlib 和 seaborn 之间的不一致图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

导入 matplotlib导入 matplotlib.pylab 作为 plt将 seaborn 作为 sns 导入进口大熊猫sns.set_style("白色")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", 数据=数据)plt.errorbar(data["x"], data["y"], yerr=data["s"])plt.show()

然而,即使绘制了相同的数据,这两个图看起来也完全不同.什么解释了这一点以及如何将误差线添加到点图中?

解决方案

看来 sns.pointplot 只是简单地使用了一个 [0...n-1] 作为 x 值,然后使用您提供的 x 值来标记 x 轴上的刻度.您可以通过查看输出 [-0.5, 4.5]ax.get_xlim() 来检查.因此,当您向 plt.plot 提供实际的 x 值时,它们似乎位于错误的位置.

我不会说这是一个错误,因为 seaborn 认为 pointplot 的输入是分类的(这里是

i am trying to add errorbars using plt.errorbar to a pointplot in seaborn:

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

however the two plots look totally different even though the identical data is being plotted. what explains this and how can errorbars be added to a pointplot?

解决方案

It seems that sns.pointplot simply uses an array of [0...n-1] as x values and then uses the x values that you provide to label the ticks on the x-axis. You can check that by looking at ax.get_xlim() which outputs [-0.5, 4.5]. Therefore, when you provide the actual x values to plt.plot they just seem to be at a wrong position.

I wouldn't say that this is a bug, since seaborn considers the input to pointplot to be categorial (here's the documentation for more info)

You can solve this for your simple example by mimicking seaborns behavoir:

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

这篇关于Python 中 matplotlib 和 seaborn 之间的不一致图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆