Python matplotlib颜色函数

2024-04-20 07:10:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一个ColorFunction来表示python中的绘图。在

换句话说,我想调用pyplot.plot(x, y, color=c),其中c是一个向量,定义每个数据点的颜色。在

有没有办法使用matplotlib库来实现这一点?在


Tags: 数据绘图定义plotmatplotlib颜色向量color
1条回答
网友
1楼 · 发布于 2024-04-20 07:10:00

据我所知,Matplotlib中没有等价物,但是我们可以通过两个步骤得到类似的结果:用不同颜色的点绘制点和绘制直线。在

这是一个演示。在

enter image description here


源代码

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import random

fig, ax = plt.subplots()

nrof_points = 100 
x = np.linspace(0, 10, nrof_points)
y = np.sin(x)
colors = cm.rainbow(np.linspace(0, 1, nrof_points))     # generate a bunch of colors

# draw points
for idx, point in enumerate(zip(x, y)):
    ax.plot(point[0], point[1], 'o', color=colors[idx], markersize=10)

# draw the line
ax.plot(x, y, 'k')
plt.grid()

plt.show()

相关问题 更多 >