matplotlib - 如何在 seaborn 线图中使用自定义误差线

标签 matplotlib data-visualization seaborn

我正在使用 seaborn.lineplot生成一些时间序列图。我在两个列表中预先计算了一种特定类型的误差线,例如 upper=[1,2,3,4,5] lower=[0,1,2,3,4] .有没有办法可以在这里自定义错误栏,而不是在 lineplot 中使用 CI 或 Std 错误栏?

最佳答案

如果您想要 seaborn.lineplot 以外的错误带/条提供,您必须自己绘制它们。下面是几个示例,说明如何在 matplotlib 中绘制误差带和误差条,并获得与 seaborn 中相似的绘图。它们是使用作为 pandas 数据框导入的 fmri 示例数据集构建的,并且基于 lineplot function 上的 seaborn 文档中显示的示例之一。 .

import numpy as np                 # v 1.19.2
import pandas as pd                # v 1.1.3
import matplotlib.pyplot as plt    # v 3.3.2
import seaborn as sns              # v 0.11.0

# Import dataset as a pandas dataframe
df = sns.load_dataset('fmri')

# display(df.head(3))
  subject  timepoint event    region    signal
0     s13         18  stim  parietal -0.017552
1      s5         14  stim  parietal -0.080883
2     s12         18  stim  parietal -0.081033
该数据集包含一个称为时间点的时间变量,在 19 个时间点中的每一个时间点对信号进行 56 次测量。我使用默认的估计器,即平均值。为了简单起见,我没有使用平均值标准误差的置信区间作为不确定性(也称为误差)的度量,而是使用每个时间点的测量值的标准偏差。这是在 lineplot 中设置的通过 ci='sd' ,误差在均值的每一侧都扩展到一个标准差(即对称)。这是带有误差带的 seaborn 线图的样子(默认情况下):
# Draw seaborn lineplot with error band based on the standard deviation
fig, ax = plt.subplots(figsize=(9,5))
sns.lineplot(data=df, x="timepoint", y="signal", ci='sd')
sns.despine()
plt.show()
sns_lineplot_errband
现在假设我更愿意使用一个误差带,该误差带跨越平均值两侧每个时间点测量值的标准偏差的一半。因为调用 lineplot 时无法设置此首选项函数,据我所知,最简单的解决方案是使用 matplotlib 从头开始​​创建绘图。
# Matplotlib plot with custom error band

# Define variables to plot
y_mean = df.groupby('timepoint').mean()['signal']
x = y_mean.index

# Compute upper and lower bounds using chosen uncertainty measure: here
# it is a fraction of the standard deviation of measurements at each
# time point based on the unbiased sample variance
y_std = df.groupby('timepoint').std()['signal']
error = 0.5*y_std
lower = y_mean - error
upper = y_mean + error

# Draw plot with error band and extra formatting to match seaborn style
fig, ax = plt.subplots(figsize=(9,5))
ax.plot(x, y_mean, label='signal mean')
ax.plot(x, lower, color='tab:blue', alpha=0.1)
ax.plot(x, upper, color='tab:blue', alpha=0.1)
ax.fill_between(x, lower, upper, alpha=0.2)
ax.set_xlabel('timepoint')
ax.set_ylabel('signal')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()
mpl_lineplot_errband
如果您更喜欢有误差线,这就是 seaborn 线图的样子:
# Draw seaborn lineplot with error bars based on the standard deviation
fig, ax = plt.subplots(figsize=(9,5))
sns.lineplot(data=df, x="timepoint", y="signal", ci='sd', err_style='bars')
sns.despine()
plt.show()
sns_lineplot_errbars
以下是如何使用自定义误差线获得与 matplotlib 相同类型的绘图:
# Matplotlib plot with custom error bars

# If for some reason you only have lists of the lower and upper bounds
# and not a list of the errors for each point, this seaborn function can
# come in handy:
# error = sns.utils.ci_to_errsize((lower, upper), y_mean)

# Draw plot with error bars and extra formatting to match seaborn style
fig, ax = plt.subplots(figsize=(9,5))
ax.errorbar(x, y_mean, error, color='tab:blue', ecolor='tab:blue')
ax.set_xlabel('timepoint')
ax.set_ylabel('signal')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()

# Note: in this example, y_mean and error are stored as pandas series
# so the same plot can be obtained using this pandas plotting function:
# y_mean.plot(yerr=error)
mpl_lineplot_errbars
Matplotlib 文档:fill_between , specify error bars , subsample error bars
Pandas 文档:error bars

关于matplotlib - 如何在 seaborn 线图中使用自定义误差线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203420/

相关文章:

python - 以预定义的宽度/高度比保存右侧带有图例的 matplotlib 图

r - 使用 k-means 在 R 中可视化大维簇

Python - Seaborn fiddle 情节,没有做我想做的事

python - 在子图中旋转刻度标签(Pyplot、Matplotlib、gridspec)

python - pyplot : Plotting scatter plot with multiple Y values and categorical X values

python - Python中的树形图可视化

javascript - D3.js: "On the fly"添加到数组的元素不刷新 svg 图形

python - 注释改变情节?

plot - Seaborn 群图和点图躲避对齐

python - Jupyter 笔记本中未显示的绘图