Reputation: 11
I am trying to plot the curve x/log(x) onto the following graph:
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()
I have tried adding the following line of code but this causes an error:
plt.plot(x,x/(m.log(x))
If anyone could help it would be greatly appreciated!
Upvotes: 1
Views: 1463
Reputation: 1967
It only makes sense to use positive values for x
else the log is undefined, and to ensure x
is not equal to one, else we will encounter a division by zero scenario.
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.
This produces the following plot:
Why your code might be failing?
It is unclear what m
is (the math
module?). It may be division by zero error. I suspect it might be the container for x
, as standard list by list division may not give the expected results. I would recommend using the numpy.array
container, as most operations would be element wise, which is likely what you are looking for.
A nicer plot:
The following I think looks nicer.
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")
Upvotes: 5