简体   繁体   English

如何使用colormap绘制matplotlib线图?

[英]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? 如何使用python matplotlib创建线图,使线的颜色相对于另一个系列变化?

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'. 我只想以某种方式绘制图形(t,y),即线条颜色表示遵循特定颜色图(cmap)(例如“等离子”)的z值。

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). 这个问题被标记为可能重复,但引用的问题是期望的结果是改变颜色的线以帮助遵循绘制的路径(序列信息),而不是在另一个值上添加信息(在本例中为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: 使用您回答的问题的答案中引用的colorline函数不是this的重复项 ,可以这样做:

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 . 这将创建多个线段,每个线段的颜色由z决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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