3
\$\begingroup\$

As a beginner this is my first code. Any comments?

import numpy as np
import math
import matplotlib.pylab as plt

x=np.linspace(-360,360,45)*np.pi/180
plt.subplot(111)
_sin=plt.plot(x, np.sin(x),label="Sine Curve")
_cos=plt.plot(x,np.cos(x),label="Cos Curve")
#_tan=plt.plot(x,np.tan(x),label="Tan Curve")
plt.legend(['sin','cos','tan'])

plt.show()#This line might be required on some python implementations. 
\$\endgroup\$
2
  • 4
    \$\begingroup\$ (To split an excessively fine hair, not specifying in any way what the code is to accomplish (beyond naming a theme) makes it correspondingly hard to tell whether the code works as intended.) \$\endgroup\$
    – greybeard
    Dec 9, 2020 at 7:50
  • \$\begingroup\$ @greybeard Considering the title, I think it's supposed to plot (co)sine waves. \$\endgroup\$
    – Mast
    Dec 9, 2020 at 21:12

2 Answers 2

3
\$\begingroup\$

In addition to SuperStormer's points ...

Unused variables

_sin and _cos are never used. You don't need to assignments to these variable.

Naming conventions

In the event you will eventually use them...

Leading underscore are used to indicate private members of a class. To avoid collisions with keywords, by convention, a trailing underscore is used (i.e. sin_ & cos_).

Unused arguments

'tan' is being passed to plt.legend(), but there is no tangent plot.

It works, but it is a bad habit to get into. Pass the desired curve titles directly to the plt.plot() function (i.e., label="sin"), and simply call plt.legend() with no arguments.

Magic numbers

What is 111 and why are you passing it to subplot()?

Updated code

import numpy as np
import matplotlib.pylab as plt

x = np.linspace(-360, 360, 45) * np.pi / 180

plt.subplot()
sin_ = plt.plot(x, np.sin(x), label="sin")
cos_ = plt.plot(x, np.cos(x), label="cos")
#tan_ = plt.plot(x, np.tan(x), label="tan")

plt.legend()

# plt.show()   # For CPython
\$\endgroup\$
0
2
\$\begingroup\$

First, use pyplot instead of pylab.

Secondly, check out PEP 8, the Python style guide. stdlib imports should be at the very top, then 3rd-party imports. However, math isn't even used anywhere, so you can just remove the import entirely.

In addition, your spacing is a bit inconsistent. Assignments should have 1 space on each side and there should be a space after the commas within a func call. I recommend using an auto-formatter to fix these stylistic issues, such as black or yapf.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.