KaZyKa
KaZyKa

Reputation: 325

python matplotlib for loop plot with function and labels

I am trying to plot multiple functions from a array, with labels.

So I found some help from here: https://stackoverflow.com/a/11493343/4055341 and tried to modify the code as it can be seen below. But I get an error with this. SO the error I get is ValueError, but how can I make them the same size?

import numpy as np
import matplotlib.pyplot as plt


x = np.linspace(0, 10, 100)

y = [[5*x], [1*x], [2*x]]

labels = ['foo', 'bar', 'baz']

for y_arr, label in zip(y, labels):
    plt.plot(x, y_arr, label=label)

plt.legend()
plt.show()

Upvotes: 0

Views: 441

Answers (1)

Matheus Portela
Matheus Portela

Reputation: 2460

Replacing y = [[5*x], [1*x], [2*x]] by y = [5*x, 1*x, 2*x] should be enough to solve your problem.

Reasoning:

When you did x = np.linspace(0, 10, 100), x became a Numpy array similar to x = [0, 0.1010, 0.2020, 0.3030, ..., 9.7979, 9.8989, 10]. Multiplying x by a scalar generates a new Numpy array with the same size, such as 5*x = [0, 0.505, 1.01, 1.515, ..., 48.989, 49.494, 50]. Hence, y = [5*x, 1*x, 2*x] will be a list with each element being a proper Numpy array.

Visually, it is like this:

y = [
    [0, 0.1010, 0.2020, 0.3030, 9.7979, 9.8989, 10],
    [0, 0.505, 1.01, 1.515, 48.9895, 49.4945, 50],
    [0, 0.202, 0.404, 0.606, 19.5958, 19.7978, 20]
]

On the other hand, y = [[5*x], [1*x], [2*x]] is a list containing 3 lists, each containing only a single object: the Numpy array resulting from the multiplication. This is the result:

y = [
    [
        [0, 0.1010, 0.2020, 0.3030, 9.7979, 9.8989, 10]
    ],
    [
        [0, 0.505, 1.01, 1.515, 48.9895, 49.4945, 50]
    ],
    [
        [0, 0.202, 0.404, 0.606, 19.5958, 19.7978, 20]
    ]
]

That's why plot breaks: it was expecting an array as long as x but, instead, y_arr is assigned to [[0, 0.1010, 0.2020, 0.3030, 9.7979, 9.8989, 10]] for instance: a list with only one object (which happens to be a Numpy array).

Upvotes: 1

Related Questions