簡體   English   中英

如何使用第三個變量按顏色分隔數據的散點圖 plot?

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

我的問題與以下問題非常相似: python - scatter plot with dates and 3rd variable as color

但我希望 colors 根據我的第三個變量中的 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來改變colors。

我嘗試使用另一個問題中介紹的簡單代碼:

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

但我不知道該怎么做。

結果將是一個散點,由 colors 分隔的點由第三列“半徑”中的值引導,但我使用第一個代碼得到的所有點都是黑色的,或者,通過使用第二個代碼它告訴我我是一個字符串,我不能把它放在一個列表中:(

我怎樣才能做到這一點?

我認為你應該做的是:

  1. 創建一個空list ,稍后將傳遞給分散 function 中的“c”。
  2. 根據您提到的離散化,迭代您的數據並執行 if 語句的“switch like”序列以將 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()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM