我的问题与SO上的以下主题密切相关:Fit straight line on semi-log scale with Matplotlib
但是,我想在X轴是对数而Y轴是线性的图表中创建一条最佳拟合线。
import matplotlib.pyplot as plt
import numpy as np
plt.scatter(players['AB'], players['Average'], c='black', alpha=0.5)
p = np.polyfit(players['AB'], players['Average'], 1)
plt.plot(players['AB'], p[0] + p[1] * np.log(players['AB']), color='r', linestyle='dashed', alpha=0.7)
plt.xscale('log')
plt.xlim(1, 25000)
plt.ylim(-0.05, 0.60)
plt.xlabel('Number of at-bats (AB)')
plt.ylabel('Batting Average')
plt.show()
这为我提供了以下内容:
我做错了什么?谢谢
编辑
p = np.polyfit(np.log(players['AB']), players['Average'], 1)
plt.plot(players['AB'], p[0] + p[1] * np.log(players['AB']), color='r', linestyle='dashed', alpha=0.7)
这仍然给了我错误的最佳匹配:
发布于 2019-02-22 07:06:58
我相信你需要做的是
p = np.polyfit(np.log(players['AB']), players['Average'], 1)
plt.plot(players['AB'], p[0] * np.log(players['AB']) + p[1])
当在x轴半对数空间中绘制时,这将为您提供线性多项式拟合。下面是一个完整的示例来演示这一点
import matplotlib.pyplot
import numpy as np
n = 100
np.random.seed(1)
x = np.linspace(1,10000,n)
y = np.zeros(n)
rand = np.random.randn(n)
for ii in range(1,n):
x[ii] = 10**(float(ii)/10.0) # Create semi-log linear data
y[ii] = rand[ii]*10 + float(ii) # with some noise in the y values
plt.scatter(x,y)
p = np.polyfit(np.log(x), y, 1)
plt.semilogx(x, p[0] * np.log(x) + p[1], 'g--')
plt.xscale('log')
plt.show()
对于生成的样本数据,这将为您提供
https://stackoverflow.com/questions/54814435
复制相似问题