我的问题与以下关于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)
答案 0 :(得分:1)
我相信您需要做
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()
对于生成的示例数据,这可以为您提供