Issue
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')
Solution
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)
If you just want colored horizontal lines:
plt.hlines([0, 1, 2], 0, 4, ['r', 'b', 'g'])
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()
Additional options:
- PyViz: Python data visualization landscape
- Line Collection from matplotlib
- As pointed out by ImportanceOfBeingErnest
- Many plots in less time - python
- python/matplotlib - multicolor line
Answered By - Trenton McKinney
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.