我有一個折線圖顯示每年的事件數量,還有一條當前顯示平均事件數量的輔助線。我在我的圖表中注意到 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,)
我理解這個錯誤,但我想知道如何實作我的目標。這是我當前的輸出:

uj5u.com熱心網友回復:
您可以使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/396831.html
標籤:Python 熊猫 matplotlib
上一篇:Matplotlib影片未完成
