使用Python将y = x / log(x)的图添加到图形中

时间:2017-01-07 12:07:48

标签: python matplotlib

我试图将曲线x / log(x)绘制到下图中:

plt.figure(1)
plt.plot(x,x,"r")
plt.title("Happy Numbers v y=x v y=x/log(x)")
plt.ylabel("Number of Happy Numbers")
plt.xlabel("Number Tested")
plt.plot(x,y,'.')
plt.show()

我尝试添加以下代码行,但这会导致错误:

plt.plot(x,x/(m.log(x))

如果有人能提供帮助,我们将不胜感激!

1 个答案:

答案 0 :(得分:5)

只有x使用正值才有意义,否则日志未定义,并且为了确保x不等于1,否则我们将遇到除零情景。

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1.1, 10, 100)
y = x/np.log(x)
plt.clf()
# plt.figure(1) # I am not sure we need this?
plt.plot(x,x,"r")
plt.title("Happy Numbers v y=x v y=x/log(x)")
plt.ylabel("Number of Happy Numbers")
plt.xlabel("Number Tested")
plt.plot(x,y,'.')
# plt.show() # See previous comment.

这会产生以下情节:

MWE

为什么您的代码可能会失败? 目前还不清楚m是什么(math模块?)。它可能被零除错误。我怀疑它可能是x的容器,因为列表分区的标准列表可能不会给出预期的结果。我建议使用numpy.array容器,因为大多数操作都是元素明智的,这很可能就是你要找的东西。

更好的情节:

以下我认为看起来更好。

import numpy as np
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import rc
import matplotlib.pyplot as plt
x = np.linspace(1.1, 10, 100)
y = x / np.log(x)
plt.clf()  # Ensures a clean plotting canvas.
plt.rc('text', usetex=True)
plt.rc('figure', figsize=(8, 6))
plt.rc('font', family='serif', serif=['Computer Modern Roman'], size=16)
plt.plot(x, x, "k-", label='$x$')
plt.title("Happy Numbers $v$")
plt.ylabel("Number of Happy Numbers")
plt.xlabel("Number Tested")
plt.plot(x, y, 'k--', label='$x/\\log(x)$')
plt.legend(loc='upper center', frameon=False, handlelength=3)
plt.savefig('example.pdf', format="pdf")

nicer plot