Matplotlib趋势线代码能运行但不绘制p(x)线...我不知道哪里出错。

0 投票
1 回答
4064 浏览
提问于 2025-04-18 14:50

请帮帮我... 我无法绘制这条线。虽然可以绘制出x和y的散点图,但趋势线却不显示。

import numpy as np
import matplotlib.pyplot as fs
name = ["SlowFast","Bedrock","MeanSlow","hAgDenkm","hSinDenkm","hAgSl","hAgFa","hSinSl","hSinF","LogSlowFast","LogBedrock","LogMeanSlow","LoghAgDenkm",#
             "LoghSinDenkm","LoghAgSl","LoghAgFa","LoghSinSl","LoghSinFa"]
data = np.genfromtxt('C:\Users\Ben\Documents\R\LWM_Study\LWM52714BigRun.csv',dtype = 'float' , delimiter = ',' , skip_header = 0, skip_footer= 20 , names = name) ### data array###

x=data["LogSlowFast"]
y=data["LoghSinDenkm"]
z = np.polyfit(x,y,1)
p = np.poly1d(z)
fs.plot(x,y,'ro',x,p(x),'r--')
fs.ylabel("a")
fs.xlabel("LogSlowFast")
fs.show()

print x,y,z,p

1 个回答

1

你的数据 xy 可能有问题。如果你把代码的前半部分换成一些假数据:

x=np.linspace(0,1,100)
y=x**2
z = np.polyfit(x,y,1)
p = np.poly1d(z)
fs.plot(x,y,'ro',x,p(x),'r--')
fs.ylabel("a")
fs.xlabel("LogSlowFast")
fs.show()

你会得到:

enter image description here

所以,除了数据以外,其他的都和你的代码保持一致。

关于数据的一些有趣的事情:

  • x.dtype
  • y.dtype
  • 数据中可能有 NaN 吗?
  • p

我猜你的数据里可能有一个 nan 或者可能有一个 inf。这会导致趋势线也变成 nan,所以看不见。

也许首先要检查的是 p 的内容是否合理。

撰写回答