gpt4 book ai didi

python - 如何为散点图绘制平均线

转载 作者:太空狗 更新时间:2023-10-29 17:59:41 27 4
gpt4 key购买 nike

我的数据如下:

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

最佳答案

这可以通过从您的数据生成一个新的 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()

结果图: enter image description here

关于python - 如何为散点图绘制平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12043672/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com