简体   繁体   English

计算 matplotlib 中曲线 python 的每个点的切线

[英]Calculate tangent for each point of the curve python in matplotlib

I made one curve with a series of point.我用一系列点制作了一条曲线。 I want to calculate gradient of the jieba curve.我想计算jieba曲线的梯度。

plt.loglog(jieba_ranks, jieba_counts, linestyle='-', label='jieba')
plt.loglog([1,jieba_counts[0]],[jieba_counts[0],1],color='r', linestyle='--', label='zipf\'s law a =1')
plt.legend(loc="best")

plt.title("Zipf plot for jieba")
plt.xlabel("Frequency rank of token")
plt.ylabel("Absolute frequency of token")
plt.grid(True,axis="y",ls="-", which="both")

在此处输入图像描述

Edit: I used np.gradient to produce slope of jieba curve and plot it with jieba_ranks编辑:我使用 np.gradient 生成 jieba 曲线的斜率,并使用 jieba_ranks 生成 plot 它

slope_Y = np.gradient(np.log(jieba_counts), np.log(jieba_ranks))
fig1, ax1 = plt.subplots()
ax1.plot(np.log(jieba_ranks), slope_Y)

But, the gradient curve created didn't describe the relationship between the zipf and the jieba.但是,创建的渐变曲线并没有描述 zipf 和 jieba 之间的关系。 Maybe, I need calculate the distance of each point on zipf and jieba.也许,我需要计算 zipf 和 jieba 上每个点的距离。 在此处输入图像描述

numpy makes gradient available, this function would probably be useful for solving your problem numpy使gradient可用,此 function 可能对解决您的问题有用

if you add data/code to the question I can try and suggest something more sensible!如果您在问题中添加数据/代码,我可以尝试提出更明智的建议!

Next time when you ask a question, it would be helpful to include a little bit more information, maybe even show us your plot.下次当您提出问题时,包含更多信息会很有帮助,甚至可以向我们展示您的 plot。 Because the following example will give bad results if your sampling is not dense enough.因为如果您的采样不够密集,以下示例将给出不好的结果。 (if you have bad sampling you might want to fit a spline to your points and get the tangent of that curve, etc..) (如果您的采样不好,您可能希望将样条曲线拟合到您的点并获得该曲线的切线等。)

But lets go with the easiest case, when your sampling is dense enough, and your function is not noisy.但是让 go 使用最简单的情况,当您的采样足够密集并且您的 function 没有噪音时。 You can calculate the (forward) derivatives very easily the following way:您可以通过以下方式非常轻松地计算(前向)导数:

import numpy as np
import matplotlib.pyplot as plt

X = np.arange(0,np.pi*2,np.pi*2/100)
Y = np.sin(X)

slope_Y = np.diff(Y)/np.diff(X)

plt.plot(X,Y)
plt.plot(X[:-1],slope_Y)

The original curve is a sin(x), and the derivative of that curve is a cos(x), what you can easily see if you run this code.原始曲线是 sin(x),该曲线的导数是 cos(x),如果运行此代码,您可以轻松看到。

If this does not solve your problem, please include more information.如果这不能解决您的问题,请提供更多信息。

As Sam Mason suggested above you can simply use the gradient function of numpy as well.正如 Sam Mason 上面建议的那样,您也可以简单地使用 numpy 的渐变 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM