这段代码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
带有x
和y
坐标的渐变颜色?
您是否已经看过 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)
是的,但我似乎无法使其简单地工作
matplotlib中的简单线条(即Line2d对象)一次仅支持一种颜色。如果要具有颜色渐变,则需要使用LineCollections。
该技术是将线划分为小块,并用颜色绘制每个图。提供的链接显示了它的工作原理。
尽管此链接可以回答问题,但最好在此处包括答案的基本部分,并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会无效。-来自评论