我可以将点的颜色列表传递给 matplotlib 的“Axes.plot()"吗? [英] Can I pass a list of colors for points to matplotlib's 'Axes.plot()'?

查看:42
本文介绍了我可以将点的颜色列表传递给 matplotlib 的“Axes.plot()"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多要点要绘制,我注意到在 matplotlib 中单独绘制它们花费的时间更长(超过 100倍,根据 cProfile ),而不是一次绘制所有内容.

I've got a lot of points to plot and am noticing that plotting them individually in matplotlib takes much longer (more than 100 times longer, according to cProfile) than plotting them all at once.

但是,我需要对点进行颜色编码(基于与每个点相关的数据),并且无法弄清楚如何为给

However, I need to color code the points (based on data associated with each one) and can't figure out how to plot more than one color for a given call to Axes.plot(). For example, I can get a result similar to the one I want with something like

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 的值并不能以这种方式工作.

but providing a list as the value for color doesn't work in this way.

有没有办法向 Axes.plot() 提供颜色列表(就此而言,边缘颜色、面部颜色、形状、z 顺序等),以便每个可以自定义点,但可以一次绘制所有点?

Is there a way to provide a list of colors (and for that matter, edge colors, face colors , shapes, z-order, etc.) to Axes.plot() so that each point can potentially be customized, but all points can be plotted at once?

使用 Axes.scatter() 似乎可以做到这一点,因为它允许单独设置点颜色.但颜色就好像那样.(Axes.scatter() 也以完全不同的方式布置图形.)

Using Axes.scatter() seems to get part way there, since it allows for individual setting of point color; but color is as far as that seems to go. (Axes.scatter() also lays out the figure completely differently.)

推荐答案

我直接创建对象(补丁)的速度大约快了 5 倍.为了说明该示例,我更改了限制(必须使用此方法手动设置).圆形本身使用 matplotlib.path绘制.Path.circle.最小工作示例:

It is about 5 times faster for me to create the objects (patches) directly. To illustrate the example, I have changed the limits (which have to be set manually with this method). The circle themselves are draw with matplotlib.path.Path.circle. Minimal working example:

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

这篇关于我可以将点的颜色列表传递给 matplotlib 的“Axes.plot()"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆