1

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!

3
  • 3
    what was the error? what are x and y? what is m? please post a minimal, complete and verifiable example. Commented Jan 7, 2017 at 12:10
  • If m is math, then it won't work obviously. Commented Jan 7, 2017 at 12:17
  • Sorry I am new to python can you explain why it will not work because of m? Commented Jan 7, 2017 at 12:22

1 Answer 1

5

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:

MWE

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")

nicer plot

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.