簡體   English   中英

使用 seaborn.facetgrid,如何指定映射散點圖的顏色以反映數據框中列的值?

[英]With seaborn.facetgrid, how do I specify the color of a mapped scatter plot to reflect the values of a column in the data frame?

我想創建散點圖的 FacetGrid,其中點的顏色由繪制的數據框中的列定義。 但是,當我映射它時,似乎我無法將列名傳遞給plt.scatterc=參數,因為它被解釋為一串顏色而不是列名:

import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style='white')

iris = sns.load_dataset('iris')
g = sns.FacetGrid(iris, row='species', size=4)
g.map(plt.scatter, 'sepal_width', 'sepal_length', c='petal_length')

出去:

/home/user/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba_array(self, c, alpha)
    420             result = np.zeros((nc, 4), dtype=np.float)
    421             for i, cc in enumerate(c):
--> 422                 result[i] = self.to_rgba(cc, alpha)
    423             return result
    424 

/home/user/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba(self, arg, alpha)
    374         except (TypeError, ValueError) as exc:
    375             raise ValueError(
--> 376                 'to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
    377 
    378     def to_rgba_array(self, c, alpha=None):

ValueError: to_rgba: Invalid rgba arg "p"
to_rgb: Invalid rgb arg "p"
could not convert string to float: p

我預期的結果與plt.scatter(iris.sepal_width, iris.sepal_length, c=iris.petal_length)

在此處輸入圖片說明

我簡單地嘗試了sns.regplot ,但它似乎遇到了同樣的問題。 如果我不指定 FacetGrid 的row=col=參數,我可以輸入c=iris.petal_length以獲得預期結果。

有沒有辦法創建一個 FacetGrid,其中數據按行或列分組,數據點根據數據框中的列着色?

在 DataFrame 中標識為列的變量需要與繪圖函數中的位置參數相對應。 最簡單的方法是在plt.scatter周圍編寫一個小包裝函數,使其簽名scatter(x, y, c)而不是scatter(x, y, s, c)

import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style='white')

iris = sns.load_dataset('iris')
g = sns.FacetGrid(iris, row='species', size=4)

def scatter(x, y, c, **kwargs):
    plt.scatter(x, y, c=c, **kwargs)

g.map(scatter, 'sepal_width', 'sepal_length', 'petal_length')

這是你想要做的嗎?

g.map(plt.scatter, 'sepal_width', 'sepal_length', c=iris.petal_length)

您可以通過指定hue參數來實現此目的。

g = sns.FacetGrid(iris, col='species', hue='petal_length', size=4)
g.map(plt.scatter, 'sepal_width', 'sepal_length')

這產生了這個情節:這個情節 .

潛在的問題是 FacetGrid 的map函數通過將它們添加到繪圖函數的**kwargs來無意中管理color值。
如果要為散點圖指定自己的ccolor ,可以在一個小包裝器中從 kwargs 中刪除 color 參數,然后指定您自己的參數,而不會出現任何錯誤:

def custom_scatter(x, y, c, **kwargs):
  del kwargs["color"]
  plt.scatter(x, y, c = c, **kwargs)

現在您可以使用custom_scatter進行映射:

g.map(custom_scatter, 'sepal_width', 'sepal_length', 'petal_length')

暫無
暫無

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

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