Nabeel Eh
Nabeel Eh

Reputation: 35

Plotting a list of arrays on the same plot in python?

I have a list of arrays or an array of arrays that looks like

a=[array1([.....]),array2([.....]),array3([....]),.....]

and a separate array b (not a list)

b=np.array[()]

All the arrays in the list "a" are the same length and the same length as "b". I want to plot all the arrays in list "a" on the y axis verses "b" on the x axis all on the same plot. So one plot that consists of a[0]vs b, a[1] vs b, a[2] vs b,...and so on.

How can I do this?

I tried

f, axes = plt.subplots(len(a),1)
for g in range(len(a)):
    axes[g].plot(b,a[g])
    plt.show()

but this gives me many plots stacked on each other and they don't even have all the data. I want everything on one plot.

Upvotes: 1

Views: 10541

Answers (1)

sgrg
sgrg

Reputation: 1230

I just found some old code that should accomplish this. Try:

import random
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

# define a and b here

# Helps pick a random color for each plot, used for readability
rand = lambda: random.randint(0, 255)
fig = plt.figure(figsize=(10,7.5))
ax = fig.add_subplot(111)
for ydata in a:
    clr = '#%02X%02X%02X' % (rand(),rand(),rand())
    plot, = ax.plot(b, ydata, color=clr)

Edit: To generate the same set of colors every time, as answered in this post, try:

colors = cm.rainbow(np.linspace(0, 1, len(a)))
for ydata, clr in zip(a, colors):
    plot, = ax.plot(b, ydata, color=clr)

np.linspace gives you "evenly spaced numbers over a specified interval", [0,1] for this purpose.

Upvotes: 1

Related Questions