如何在pcolormesh图上进行线性回归

时间:2019-07-23 16:53:24

标签: python numpy matplotlib least-squares

我正在尝试运行最小二乘算法以将一条线放入我的数据中。

此代码类似于我的问题; “ z”是一个50 in 50的矩阵,例如,我想通过幂大于0.25的数据拟合一条线。 (按幂表示右侧的颜色条)

我想知道如何通过电源安装最佳线路?在我的数据中,x轴是时间,y轴是频率,z是功率。 而且,我的数据更加统一,因此0.25的幂几乎是线性的。

import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage.filters import gaussian_filter

# Generate data for the plot
x = np.linspace(0, 1, 51)
y = np.linspace(0, 1, 51)
r = np.random.RandomState(42)
z = gaussian_filter(r.random_sample([50, 50]), sigma=5, mode='wrap')
z -= np.min(z)
z /= np.max(z)

# Generate the plot
fig, ax = plt.subplots()
cmap = ax.pcolormesh(x, y, z)
fig.colorbar(cmap)
plt.show(fig)

我只需要一些有关如何绘制最佳拟合线的指导。

1 个答案:

答案 0 :(得分:1)

您首先需要找到最佳拟合线,并将其绘制到同一轴上

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(1,999,size=(10,4))
col = list("ABCD")
row = np.arange(1, len(data)+1)

n = len(data)   # number of bars
barwidth = 0.8  # bar width
t = 0.05
b = 0.125

# Plot
fig, ax = plt.subplots()
fig.subplots_adjust(left=0.4, top=1-t-(1-t-b)/(n+1))

ax.margins(y=(1-barwidth)/2/n)

ax.barh(row, data[:,0], height=barwidth, label="bars", )

the_table = ax.table(cellText=data,
                      rowLabels=row,
                      colLabels=col,
                      cellLoc='center',
                      bbox=(-0.6, 0.0, 0.6, (n+1) / n))

the_table.auto_set_font_size(False)
the_table.set_fontsize(9)
fig.canvas.draw()   # need to draw the figure twice

plt.yticks([])
plt.legend()
plt.show()

输出:

enter image description here

相关问题