Reputation: 489
How can I create a lineplot using python matplotlib in such a way that the color of the line varies in respect of another series?
For a simple example:
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
y = np.sin(2 * np.pi * t)
z = (t-1) ** 2
fig = plt.figure()
ax = plt.axes()
ax.plot(t, y)
ax.plot(t, z)
plt.show()
Instead of:
I would like to graph only (t, y) in a way that the line color represents the value of z following a certain colormap (cmap), for instance 'plasma'.
Edit:
This question was tagged as possibly duplicate, but references to a question where the desired result is a line changing color to help follow the path it was draw (sequence information), instead of adding information on another value (in this case z).
It is closer to this example, as pointed out in the comments, but I was looking for something simpler than having to create a set of line segments and color them individually.
Upvotes: 3
Views: 6261
Reputation: 7186
Using the colorline
function referenced in an answer to the question you said is not a duplicate of this, this can be done:
from colorline import colorline
colorline(t, y, z)
plt.xlim(t.min(), t.max())
plt.ylim(y.min(), y.max())
plt.show()
This creates multiple line segments, each with a color determined by z
.
Upvotes: 2
Reputation: 14847
I don't think there's an easy way to do it with line plots, but with scatter, it's pretty easy. If you still want a connecting line, you can fake it a bit with a gray line behind it:
ax.scatter(t, y, c=z, marker='.')
ax.plot(t, y, c='gray')
Upvotes: 1