Plotting a constant function with pyplot only works when adding and subtracting the same value. Why?

Viewed 206

I've been playing around with pyplot and some things are just weird.

import numpy as np
import matplotlib.pyplot as plt


def f(x):
    return x**2


def g(x):
    return 5


def h(x):
    return 5+x-x


x = np.linspace(-3.0, 3.0, num=50)
plt.plot(x, f(x)) #works
plt.plot(x, g(x)) #crashes
plt.plot(x, h(x)) #works
plt.grid()
plt.show()

f(x) works as expected. g(x) crashes and to draw a line I have to use the workaround in h(x). Why is that? All of these functions only return numbers but one works and the other doesn't.

1 Answers

x is a numpy array of size 50. f(x) and h(x) both return arrays of the same size. So you can plot one against the other.

g(x) returns the scalar 5, which has the size 1. And you cannot plot an array of size 50 against something with size 1.

You can modify it like so:

def g(x):
    return np.ones_like(x)*5

This returns an array of the same size (and shape) as the input array, so you can plot the input against the output.

Related