0

I want to make a spaghetti plot (lots of lines in one window) using matplotlib.pyplot. Different lines need to be different colors based on my data. However, I do not want to use a for loop for each line because I need it to work fast. I'm using matplotlib event handling and replotting over 200 lines based on mouse drag; a for loop takes too long for that.

While there isn't any documentation on this I found out that if you use plt.plot and pass on an array for x and a matrix for y it prints out multiple lines. And it's super fast. However all of them have to be the same color. And passing on an array for color results in an error.

_ = plt.plot([0,1,2,3,4], np.matrix.transpose(np.asarray([[0,0,0,0,0],[1,1,1,1,1],[2,2,2,2,2]])), color='blue', linewidth=1, alpha=0.4) 

This code produces 3 horizontal lines in one plot and takes faster than using the plot command 3 times. This is great, but i want different colors. If i do

_ = plt.plot([0,1,2,3,4], np.matrix.transpose(np.asarray([[0,0,0,0,0],[1,1,1,1,1],[2,2,2,2,2]])), color=['blue', 'red, 'green'], linewidth=1, alpha=0.4) 

I get an error Invalid RGBA argument: array(['blue', 'red', 'red'], dtype='<U4')

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
janine
  • 39
  • 7
  • remove the color arg – Derek Eden Aug 25 '19 at 05:33
  • 1
    For an efficiency comparison for drawing many lines, see [Many plots in less time](https://stackoverflow.com/questions/54492963/many-plots-in-less-time-python). An implementation of a `LineCollection` with several colors would be shown in [python/matplotlib - multicolor line](https://stackoverflow.com/a/46348309/4124317). – ImportanceOfBeingErnest Aug 25 '19 at 07:48

1 Answers1

5

Remove the color argument, and it'll happen automatically

a = [0,0,0,0,0]
b = [1,1,1,1,1]
c = [2,2,2,2,2]

plt.plot([0,1,2,3,4], np.matrix.transpose(np.asarray([a, b, c])), linewidth=1, alpha=0.4)

enter image description here

If you just want colored horizontal lines:

plt.hlines([0, 1, 2], 0, 4, ['r', 'b', 'g'])

enter image description here

Use seaborn:

  • seaborn is a high-level api for matplotlib.
import seaborn as sns
import pandas as pd

ex = pd.DataFrame({'a': [0, 0, 0],
                   'b': [1, 1, 1],
                   'c': [2, 2, 2]})

# either palette works
palette=["#9b59b6", "#3498db", "#95a5a6"]
# palette=['blue', 'red', 'green']

sns.lineplot(data=ex, palette=palette, dashes=False)
plt.show()

enter image description here

Additional options:

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158