Python 指定散点图中每个点的颜色(matplotlib)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33287156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specify color of each point in scatter plot (matplotlib)
提问by codycrossley
I have a 3D Plot that I created using matplotlib, and I have a list of rbg values that correspond to each point.
我有一个使用 matplotlib 创建的 3D 图,我有一个对应于每个点的 rbg 值列表。
I have the X, Y, and Z data, and then I have a "color list" of the form:
我有 X、Y 和 Z 数据,然后我有以下形式的“颜色列表”:
[ (r,g,b), (r,g,b), ... , (r,g,b) ]
to match each (x, y, z) point.
匹配每个 (x, y, z) 点。
Right now, I have
现在,我有
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
ax.scatter(X, Y, Z)
plt.show()
What's the appropriate way to incorporate those rgb tuples so that each point will be assigned a specific color?
合并这些 rgb 元组以便为每个点分配特定颜色的适当方法是什么?
采纳答案by Camon
I used a for
loop to individually assign each color to each point. Here is my code:
我使用for
循环将每种颜色单独分配给每个点。这是我的代码:
X = [1, 2, 3]
Y = [2, 5, 8]
Z = [6, 4, 5]
colors=["#0000FF", "#00FF00", "#FF0066"]
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
for i in range(len(X)):
ax.scatter(X[i], Y[i], Z[i], color=colors[i])
plt.show()
The for
loop goes point by point (hence the [i]
in front of each X,Y,Z value) and gives a color one by one. I used hex colors for my example, but you could probably use something else if you wanted.
所述for
环推移逐点(因此[i]
在每个X,Y,Z值的前方),并给出一个颜色之一。我在示例中使用了十六进制颜色,但如果您愿意,您可以使用其他颜色。
回答by kmader
If you don't want to use a for loop (which can be very slow for large lists) You can use the scatter command as is with an RGB color list, but you need to specify the colors as a vector of RGB (or RGBA) values between 0 and 1
如果您不想使用 for 循环(这对于大型列表可能会很慢)您可以按原样使用 scatter 命令处理 RGB 颜色列表,但您需要将颜色指定为 RGB(或 RGBA ) 0 到 1 之间的值
X = [0, 1, 2]
Y = [0, 1, 2]
Z = [0, 1, 2]
C = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]])
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
ax.scatter(X, Y, Z, c = C/255.0)
plt.show()
回答by Rainald62
Here is an example where the colors are calculated instead of specified by a literal list.
这是一个示例,其中计算颜色而不是由文字列表指定。
import matplotlib.pyplot as plt
import numpy as np
phi = np.linspace(0, 2*np.pi, 60)
x = np.sin(phi)
y = np.cos(phi)
rgb_cycle = np.vstack(( # Three sinusoids
.5*(1.+np.cos(phi )), # scaled to [0,1]
.5*(1.+np.cos(phi+2*np.pi/3)), # 120° phase shifted.
.5*(1.+np.cos(phi-2*np.pi/3)))).T # Shape = (60,3)
fig, ax = plt.subplots(figsize=(3,3))
ax.scatter(x,y, c=rgb_cycle, s=90)
fig.show()