简体   繁体   中英

How to plot a matplotlib line plot using colormap?

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.

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')

在这里输入代码

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM