繁体   English   中英

我如何延长 matplotlib plot 中的趋势线?

[英]How do i extend trend line in matplotlib plot?

这是我拥有的 plot 的一部分

我需要创建将扩展到此 plot 的第 3 季度的趋势线...我想不出任何解决方案。

import matplotlib.pyplot as plt
import warnings

warnings.filterwarnings('ignore')

x = [1, 8, 12, 20]
y = [1, 8.4, 12.5, 20]

fig = plt.figure(figsize=(20,20))
ax = fig.add_subplot()
ax.set_xlim(-30, 30)
ax.set_ylim(-20, 20)

plt.subplot().spines['left'].set_position('center')
plt.subplot().spines['bottom'].set_position('center')
plt.plot(x,y, 'b.', ms=20)
plt.minorticks_on()
ax.grid(True, which='both')
mean_line = ax.plot()
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r--")

plt.show()

我对趋势线没有任何经验,但我创建了具有不同符号的现有 x 和 y 值的组合,并绘制了下图。

import matplotlib.pyplot as plt
import warnings

warnings.filterwarnings('ignore')

x = [1, 8, 12, 20]
y = [1, 8.4, 12.5, 20]

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot()
ax.set_xlim(-30, 30)
ax.set_ylim(-20, 20)

plt.subplot().spines['left'].set_position('center')
plt.subplot().spines['bottom'].set_position('center')
plt.plot(x,y, 'b.', ms=20)
plt.minorticks_on()
ax.grid(True, which='both')
mean_line = ax.plot()

#  update
xx =np.array(x)
xx = sorted(np.concatenate((-xx, xx), axis=0))
yy =np.array(y)
yy = sorted(np.concatenate((-yy, yy), axis=0))

z = np.polyfit(xx, yy, 1)
p = np.poly1d(z)
plt.plot(xx,p(xx),"r--")

plt.show()

在此处输入图像描述

我不认为反向 x 和 y 可以完成这项工作,它仅限于通过 (0,0) 的 poly1d 我认为扩展方法应该使用拟合线本身。

所以更通用的方法是扩展 x 并使用 poly1d(z) 来计算延长线。 z 是对拟合线的描述,因此将 x 值输入 z 将绘制线。

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

warnings.filterwarnings('ignore')

x = [1, 8, 12, 20]
y = [1, 8.4, 12.5, 20]

# make an xx that with from -20 to 20
#xx =np.array(x)
#xx = sorted(np.concatenate((-xx, xx), axis=0))
xx = [-20, 20] # also work


fig, ax = plt.subplots(figsize=(10,10))
ax.set_xlim(-30, 30)
ax.set_ylim(-20, 20)

plt.subplot().spines['left'].set_position('center')
plt.subplot().spines['bottom'].set_position('center')
plt.subplot().spines['right'].set_color('none')
plt.subplot().spines['top'].set_color('none')


plt.plot(x,y, 'b.', ms=20)
plt.minorticks_on()
#ax.grid(True, which='both')
plt.subplot().grid(True, which='both')
mean_line = ax.plot()
z = np.polyfit(x, y, 1)
p = np.poly1d(z)

plt.plot(xx,p(xx),"r--")

plt.show()

如果你在 (0,0) 附近放大,你应该看到它没有通过原点。

放大到 (0,0) 附近

结果图像

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM