[英]Best fit line semilog scale with linear y-axis and log x-axis
我的问题与关于SO的以下主题密切相关: 使用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)
我相信你需要这样做
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()
对于生成的样本数据,这将为您提供
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.