此代码绘制scatterplot带有渐变颜色的 a:
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()
Run Code Online (Sandbox Code Playgroud)
但是我如何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)
Run Code Online (Sandbox Code Playgroud)