将直线拟合到matplotlib中的对数-对数曲线 [英] Fitting a straight line to a log-log curve in matplotlib

查看:214
本文介绍了将直线拟合到matplotlib中的对数-对数曲线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我有一个图,在两个轴上都是对数的.我有pyplot的loglog函数来做到这一点.这也给了我两个轴上的对数标度.

I have a plot with me which is logarithmic on both the axes. I have pyplot's loglog function to do this. It also gives me the logarithmic scale on both the axes.

现在,使用numpy,我将一条直线拟合到我拥有的一组点上.但是,当我在绘图上画这条线时,我无法获得一条直线.我得到一条曲线.

Now, using numpy I fit a straight line to the set of points that I have. However, when I plot this line on the plot, I cannot get a straight line. I get a curved line.

蓝线是所谓的直线".它没有被绘制成直线.我想使这条直线适合红点绘制的曲线

The blue line is the supposedly "straight line". It is not getting plotted straight. I want to fit this straight line to the curve plotted by red dots

这是我用来绘制点的代码:

Here is the code I am using to plot the points:

import numpy
from matplotlib import pyplot as plt
import math
fp=open("word-rank.txt","r")
a=[]
b=[]

for line in fp:
    string=line.strip().split()
    a.append(float(string[0]))
    b.append(float(string[1]))

coefficients=numpy.polyfit(b,a,1)
polynomial=numpy.poly1d(coefficients)
ys=polynomial(b)
print polynomial
plt.loglog(b,a,'ro')
plt.plot(b,ys)
plt.xlabel("Log (Rank of frequency)")
plt.ylabel("Log (Frequency)")
plt.title("Frequency vs frequency rank for words")
plt.show()

推荐答案

您的线性拟合不适用于对数图所示的相同数据.

Your linear fit is not performed on the same data as shown in the loglog-plot.

使a和b numpy数组像这样

Make a and b numpy arrays like this

a = numpy.asarray(a, dtype=float)
b = numpy.asarray(b, dtype=float)

现在您可以对它们执行操作了. loglog-plot的作用是将对数取为a和b的底数为10.您可以通过

Now you can perform operations on them. What the loglog-plot does, is to take the logarithm to base 10 of both a and b. You can do the same by

logA = numpy.log10(a)
logB = numpy.log10(b)

这是对数图可视化的内容.通过将logA和logB都绘制为常规图来进行检查.在日志数据上重复线性拟合,并在与logA,logB数据相同的图中绘制线条.

This is what the loglog plot visualizes. Check this by ploting both logA and logB as a regular plot. Repeat the linear fit on the log data and plot your line in the same plot as the logA, logB data.

coefficients = numpy.polyfit(logB, logA, 1)
polynomial = numpy.poly1d(coefficients)
ys = polynomial(b)
plt.plot(logB, logA)
plt.plot(b, ys)

这篇关于将直线拟合到matplotlib中的对数-对数曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆