【问题标题】:How do I add a horizontal standard deviation line in my chart?如何在图表中添加水平标准差线?
【发布时间】:2022-01-26 06:55:46
【问题描述】:

我有一个显示每年事件数量的折线图,以及一个当前显示平均事件数量的辅助线。我在我的图表中注意到 2020 年特别忙,因此我想添加第二条或第三条线来显示第一个和第二个标准偏差,以可视化 2020 年有多少标准偏差高于平均值。

以下是我的代码,但由于某种原因无法绘制:

y = year_group['Count']
x = year_group['year']

y_mean = [np.mean(y)]*len(x)
y_std = np.std(y)

fig,ax = plt.subplots()

data_line = ax.plot(x,y, label='Data', marker='o')
mean_line = ax.plot(x,y_mean, label='Mean', linestyle='--')
std_line = ax.plot(x,y_std,label = 'Standard deviation')

plt.show()

这是错误:

ValueError: x and y must have same first dimension, but have shapes (8,) and (1,)

我了解这个错误,但我想知道如何实现我的目标。这是我当前的输出:

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

您可以使用hlines。下面是一些示例代码:

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

y = np.random.randint(40, 60, 61)
x = pd.date_range(start='2021-03-01', end='2021-04-30', freq='D')

y_mean = np.mean(y)
y_std = np.std(y)

fig,ax = plt.subplots()

data_line = ax.plot(x,y, label='Data', marker='o')
mean_line = plt.hlines(y=y_mean, xmin=x[0], xmax=x[-1], colors='green', linestyles='--', lw=2, label='Mean')
mean_line = plt.hlines(y=[y_mean-y_std, y_mean+y_std], xmin=x[0], xmax=x[-1], colors='red', linestyles='--', lw=2, label='Std Dev')

plt.show()

编辑: 稍微扩展一下,您的代码缺少两部分:

  • y_std 是一个单元素向量,这就是错误的原因。为了绘制它,您应该像为 y_mean 一样复制它:y_std = [np.std(y)]*len(x)
  • 另外:我猜你想绘制置信带,所以你应该绘制的是y_mean +- n*y_std

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2023-03-27
    • 1970-01-01
    • 2016-03-25
    • 2015-03-06
    相关资源
    最近更新 更多