如何使用按颜色分隔数据的第三个变量制作散点图?

How to make a scatter plot with a 3rd variable separating data by color?

我的问题与以下问题非常相似:

但我希望颜色根据我的第 3 个变量中的 3 组值而变化。

例如:

#my 3rd variable consists of a column with these planet radii values:

    radii
1    70
2     6
3    54
4     3
5    0.3
...

而且我希望根据半径>8、4< 半径<8 和半径<4 来改变颜色。

我试过使用其他问题中提供的简单代码:

db=table_with_3_columns()
x=db['column a']
y=db['column b']
z=db['radii']
plt.scatter(x,y,c=z,s=30)

但我不知道如何为 z 中的不同集合指定 'c' 参数。 我也试过使用:

a=[]
for i in db['radii']
    if i>8:
       a['bigradii']=i
    elif i<4:
       a['smallradii']=i
    elif i<8 and i>4:
       a['mediumradii']=i
    return a

但我不知道如何进行。

结果将是一个散点图,点按第 3 列 'radii' 中的值引导的颜色分隔,但我使用第一个代码得到的所有点都是黑色的,或者,通过使用第二个代码告诉我我是一个字符串,我不能把它放在列表中:(

我怎样才能做到这一点?

我认为你应该做的是:

  1. 创建一个空 list,稍后将在分散函数中传递给 'c'。
  2. 根据您提到的离散化,
  3. 遍历您的数据并执行 'switch like' if 语句序列以将 1,2 或 3 添加到列表中。这些数字将代表 cmap 调色板中的不同索引(这意味着不同的颜色)

这是我的意思的一个例子:

import numpy as np
import matplotlib.pyplot as plt

# x and y will have 100 random points in the range of [0,1]
x = np.random.rand(100)
y = np.random.rand(100)
# z will have 100 numbers, in order from 1 to 100
# z represents your third variable
z = np.arange(100)

colors = []

# add 1 or 2 to colors according to the z value
for i in z:
  if i > 50:
    colors.append(2)
  else:
    colors.append(1)

# half the points will be painted with one color and the other half with another one

plt.scatter(x, y, c=colors,)
plt.show()