如何在MatPlotLib中绘制散点图/平局图的平均线?

时间:2012-08-20 19:14:32

标签: python matplotlib

我的数据如下:

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

我可以获得以下两张图。

enter image description here

enter image description here

然而,我想要的是 this (沿途所有点的平均值): enter image description here

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)))

2 个答案:

答案 0 :(得分:13)

我认为这可以通过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()

结果数字enter image description here

答案 1 :(得分:2)

是的,您必须自己进行计算。 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)