gpt4 book ai didi

python - Seaborn 和 Stripplot 的误差线

转载 作者:太空狗 更新时间:2023-10-30 01:12:24 25 4
gpt4 key购买 nike

我在使用 Seaborn 在 Python 中创建的绘图中添加误差条时遇到了一些困难。

我目前有一个“csv”格式的数据框;

TSMdatabase = 'TSMvsRunmaster.csv';
tsmdf = pd.read_csv(TSMdatabase, sep=',');

Dataframe 的标题格式如下:

Run,TSMX_Value,TSMX_Error,TSMX+1_Value,TSMX+1_Error,Source

然后我使用 for 循环读取不同的 TSM 值:

TSM = ['001', '002', '003', '004', '010', '011', '012', 
'013', '016', '017', '101', '102', '104', '105', '106']

for x in TSM:
tsm = x

最后我密谋给我:

plt.figure()
sns.set_style("darkgrid")
ax = sns.stripplot(x="Run", y='TSM'+str(tsm)+'_Value', hue="Source", data=tsmdf,
jitter=True, palette="Set2", split=True)
plt.xticks(rotation=40)
plt.title('Run TSM'+str(tsm)+' Comparison')
plt.show()

某些 TSM 的绘图没有错误栏
Plot for certain TSM without Error Bars

如果我随后尝试添加错误栏,我最终会在每个子数据集的中间只有一个错误栏:

enter image description here

每个来源,Python 和 Matlab 实际上在数据框中都有自己的错误!

有没有人有什么想法!真的非常感谢!

最佳答案

绘制均值 + 误差比 sns.stripplot() 更适合 sns.pointplot()。这在 Seaborn 文档中有说明:

sns.pointplot Show point estimates and confidence intervals using scatter plot glyphs. A point plot represents an estimate of central tendency for a numeric variable by the position of scatter plot points and provides some indication of the uncertainty around that estimate using error bars.

sns.stripplot Draw a scatterplot where one variable is categorical. A strip plot can be drawn on its own, but it is also a good complement to a box or violin plot in cases where you want to show all observations along with some representation of the underlying distribution.

如果您可以访问所有观察结果,而不仅仅是均值 + 误差,则可以通过以下方式简单地实现您想要的:

import seaborn as sns
%matplotlib inline

tips = sns.load_dataset('tips')
sns.pointplot('sex', 'tip', hue='smoker',
data=tips, dodge=True, join=False)

enter image description here

您可以使用 ci 参数更改默认 95% 的置信区间类型:

sns.pointplot('sex', 'tip', hue='smoker',
data=tips, dodge=True, join=False, ci='sd')

enter image description here

在上面,Seaborn 计算了误差和集中趋势的测量值。如果您已经预先计算了这些,那就有点棘手了,因为目前无法将 sns.pointplot() 与预先计算的误差条一起使用。在使用 sns.pointplot() 绘制均值后,我使用 plt.errorbar() 添加了错误:

ax = sns.pointplot('sex', 'tip', hue='smoker',
data=tips, dodge=True, join=False, ci=None)

# Find the x,y coordinates for each point
x_coords = []
y_coords = []
for point_pair in ax.collections:
for x, y in point_pair.get_offsets():
x_coords.append(x)
y_coords.append(y)

# Calculate the type of error to plot as the error bars
# Make sure the order is the same as the points were looped over
errors = tips.groupby(['smoker', 'sex']).std()['tip']
colors = ['steelblue']*2 + ['coral']*2
ax.errorbar(x_coords, y_coords, yerr=errors,
ecolor=colors, fmt=' ', zorder=-1)

enter image description here

您也可以直接对整个图使用 matplotlib,如果您手动提供 x 位置,类似于 this example .

关于python - Seaborn 和 Stripplot 的误差线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43159528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com