Python matplotlib散点图:根据给定条件更改数据点的颜色

2024-06-09 13:53:57 发布

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

我有以下数据(四个等长数组):

a = [1, 4, 5, 2, 8, 9, 4, 6, 1, 0, 6]
b = [4, 7, 8, 3, 0, 9, 6, 2, 3, 6, 7]
c = [9, 0, 7, 6, 5, 6, 3, 4, 1, 2, 2]
d = [La, Lb, Av, Ac, Av, By, Lh, By, Lg, Ac, Bt]

我正在制作阵列a、b、c的三维绘图:

import pylab
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(a,b,c)

plt.show()

现在,我想使用名为“d”的数组给这些分散的点上色,如果d中对应的“I”元素值的第一个字母是“L”,那么将点上色为红色,如果它以“A”开头,则将其上色为绿色,如果它以“B”开头,则将其上色为蓝色。

所以,第一个点(1,4,9)应该是红色,第二个点(4,7,0)也应该是红色,第三个点(5,8,7)应该是绿色等等。。

有可能吗?如果你有什么想法,请帮忙:)


Tags: 数据importbyfigplt数组axla
2条回答

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter

c : color or sequence of color, optional, default

“c可以是单个颜色格式字符串,或者是长度为N的一系列颜色规范,或者是要使用通过kwargs指定的cmap和norm映射到颜色的一系列N个数字(见下文)。请注意,c不应是单个数字RGB或RGB a序列,因为这与要进行颜色映射的值数组不可区分。不过,c可以是一个二维数组,其中的行是RGB或RGBA。”

你试过这个吗?

正如scatter的文档所解释的,您可以传递c参数:

c : color or sequence of color, optional, default

c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. c can be a 2-D array in which the rows are RGB or RGBA, however.

所以有点像

use_colours = {"L": "red", "A": "green", "B": "blue"}
ax.scatter(a,b,c,c=[use_colours[x[0]] for x in d],s=50)

应该产生

coloured points

相关问题 更多 >