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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.