簡體   English   中英

如何在MatPlotLib中繪制散點圖/平局圖的平均線?

[英]How to take draw an average line for a scatter / a plot in MatPlotLib?

我的數據如下:

x = [3,4,5,6,7,8,9,9]
y = [6,5,4,3,2,1,1,2]

我可以獲得以下兩個圖表。

在此輸入圖像描述

在此輸入圖像描述

但是,我想要的是這個 (沿途所有點的平均值): 在此輸入圖像描述

在matplotlib中有可能嗎? 或者我必須手動更改列表並以某種方式創建:

x = [3,4,5,6,7,8,9]
y = [6,5,4,3,2,1,1.5]

相關代碼

ax.plot(x, y, 'o-', label='curPerform')
x1,x2,y1,y2 = ax.axis()
x1 = min(x) - 1 
x2 = max(x) + 1
ax.axis((x1,x2,(y1-1),(y2+1)))

我認為這可以通過y_mean = [np.mean(y) for i in x]執行y_mean = [np.mean(y) for i in x]

示例

import matplotlib.pyplot as plt
import random
import numpy as np


# Create some random data
x = np.arange(0,10,1)
y = np.zeros_like(x)    
y = [random.random()*5 for i in x]

# Calculate the simple average of the data
y_mean = [np.mean(y)]*len(x)

fig,ax = plt.subplots()

# Plot the data
data_line = ax.plot(x,y, label='Data', marker='o')

# Plot the average line
mean_line = ax.plot(x,y_mean, label='Mean', linestyle='--')

# Make a legend
legend = ax.legend(loc='upper right')

plt.show()

得出的數字 在此輸入圖像描述

是的,你必須自己做計算。 plot繪制您給出的數據。 如果要繪制其他一些數據,則需要自己計算該數據,然后進行繪制。

編輯:快速計算方法:

>>> x, y = zip(*sorted((xVal, np.mean([yVal for a, yVal in zip(x, y) if xVal==a])) for xVal in set(x)))
>>> x
(3, 4, 5, 6, 7, 8, 9)
>>> y
(6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 1.5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM