作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的数据如下:
x = [3,4,5,6,7,8,9,9]
y = [6,5,4,3,2,1,1,2]
然后我可以得到下面两张图。
和
但是,我想要的是this(一路上所有点的平均值):
在 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
来完成,然后使用对 ax.plot()
的额外调用将其绘制在同一绘图轴上,其中:
x
与散点图中使用的 x
相同y
是一个迭代器,具有您重复计算的“平均”值,因此它的长度等于 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()
结果图:
关于python - 如何为散点图绘制平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12043672/
我是一名优秀的程序员,十分优秀!