温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to plot a gradient color line?
matplotlib python

python - 如何绘制渐变色线?

发布于 2021-02-04 01:11:28

这段代码scatterplot用渐变颜色绘制了一个

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(30)
y = x
t = x

plt.scatter(x, y, c=t)
plt.colorbar()
plt.show()

在此处输入图片说明

但是如何绘制line带有xy坐标的渐变颜色

查看更多

提问者
Artur Müller Romanov
被浏览
77
Alperino 2020-10-09 01:50

您是否已经看过 https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html


编辑:如评论中所建议,一个最小的工作示例可能是

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x    = np.linspace(0,1, 100)
y    = np.linspace(0,1, 100)
cols = np.linspace(0,1,len(x))

points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

fig, ax = plt.subplots()
lc = LineCollection(segments, cmap='viridis')
lc.set_array(cols)
lc.set_linewidth(2)
line = ax.add_collection(lc)
fig.colorbar(line,ax=ax)

在此处输入图片说明