1

I'm a noob practicing how to use pylab, matplot lib etc.

Somehow I'm not able to plot this simple branched sin(x) function in pylab/matplotlib.

from math import sin
import pylab as plb

def f(x):
    if sin(x) > 0:
        return sin(x)
    else:
        return 0

x = plb.linspace(-4,4,10000)

plb.plot(x,f(x))
plb.show()

The following error outputs when I run the program:

Traceback (most recent call last):
  File "C:/Users/...plot.py", line 12, in <module>
    plb.plot(x,f(x))
  File "C:/Users/......plot.py", line 5, in f
    if sin(x) > 0:
TypeError: only size-1 arrays can be converted to Python scalars

Is there anyone who can help me out?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • 1
    At the risk of distracting from the question: matplotlib's official docs have discouraged the use of the `pylab` module since at least 2018: https://stackoverflow.com/questions/16849483/which-is-the-recommended-way-to-plot-matplotlib-or-pylab – Peter Leimbigler Sep 19 '21 at 20:12

1 Answers1

2

The inbuilt sine function inside math module accepts only a scalar value. You can use numpy sine instead to accomplish your plot as it accepts an array.

import numpy as np
import pylab as plb


def f(x):
    sine_ =  np.sin(x)
    sine_[sine_< 0] = 0
    return sine_
    
x = plb.linspace(-4,4,10000)

plb.plot(x,f(x))
plb.show()

The output is as shown below:

[enter image description here]

However, as pointed out by Trenton McKinney, this answer states the use of pylab is no longer recommended. So, the alternate solution using matplotlib.pyplot is shown below:

import numpy as np
import matplotlib.pyplot as plt


def f(x):
    sine_ =  np.sin(x)
    sine_[sine_< 0] = 0
    return sine_
    
x = np.linspace(-4,4,10000)

plt.plot(x,f(x))
plt.show()

The output is the same as the image above.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
lifezbeautiful
  • 1,160
  • 8
  • 13