How to plot a gradient color line?

巧了我就是萌 提交于 2021-01-29 14:27:50

问题


This code plots a scatterplot with gradient colors:

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

but how would I plot a gradient color line with a x and y coordinate?


回答1:


Did you already have a look at https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html?


EDIT: as suggested in the comments, a minimal working example could be

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)



来源:https://stackoverflow.com/questions/64267329/how-to-plot-a-gradient-color-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!