我可以将颜色列表传递给matplotlib的'Axes.plot()'吗?
我有很多数据点需要绘制,但我发现一个一个地在 matplotlib 中绘制这些点要花费很长时间(根据 cProfile 的说法,时间超过了 100 倍)。
不过,我需要根据每个点相关的数据来给这些点上色,但我不知道怎么在调用 Axes.plot()
时给多个点上不同的颜色。例如,我可以用类似下面的代码得到一个接近我想要的结果:
fig, ax = matplotlib.pyplot.subplots()
rands = numpy.random.random_sample((10000,))
for x in range(10000):
ax.plot(x, rands[x], 'o', color=str(rands[x]))
matplotlib.pyplot.show()
但我更希望能用一种更快的方法,比如:
fig, ax = matplotlib.pyplot.subplots()
rands = numpy.random.random_sample((10000,))
# List of colors doesn't work
ax.plot(range(10000), rands, 'o', color=[str(y) for y in rands])
matplotlib.pyplot.show()
但是,给 color
提供一个颜色列表并不能这样工作。
有没有办法给 Axes.plot()
提供一个颜色列表(还有边框颜色、面颜色、形状、层级等)呢?这样每个点都可以单独定制,但所有点又能一次性绘制出来?
使用 Axes.scatter()
似乎可以部分解决这个问题,因为它允许单独设置每个点的颜色;但似乎只支持颜色这一项。(Axes.scatter()
还会以完全不同的方式布局图形。)
1 个回答
2
我直接创建这些对象(补丁)快了大约5倍。为了说明这个例子,我手动调整了限制(这个方法需要手动设置限制)。这些圆形是用 matplotlib.path.Path.circle
这个工具画出来的。下面是一个最小的可运行示例:
import numpy as np
import pylab as plt
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
fig, ax = plt.subplots(figsize=(10,10))
rands = np.random.random_sample((N,))
patches = []
colors = []
for x in range(N):
C = Circle((x/float(N), rands[x]), .01)
colors.append([rands[x],rands[x],rands[x]])
patches.append(C)
plt.axis('equal')
ax.set_xlim(0,1)
ax.set_ylim(0,1)
collection = PatchCollection(patches)
collection.set_facecolor(colors)
ax.add_collection(collection)
plt.show()