簡體   English   中英

使用 Seaborn 繪制多列 pandas DataFrame

[英]Plot multiple columns of pandas DataFrame using Seaborn

假設我有包含列['X_Axis','col_2','col_3',...,'col_n',]

我需要在 X 軸上繪制第一列,然后在 Y 軸上繪制。 僅供參考:所有值都已根據 X 軸進行分組,X 軸值的范圍為0-25 ,所有其他列值已標准化為0 - 1的比例。 我希望它在同一個圖表上,而不是子圖中。

首選:FactorPlot,正態線圖。

  • 一些 seaborn 地塊將接受寬數據sns.pointplot(data=df, x='X_Axis', y='col_2') ,但不sns.pointplot(data=df, x='X_Axis', y=['col_2', 'col_3']) ,因此最好重塑 DataFrame。
  • 使用pandas.DataFrame.melt將 DataFrame 從寬變長。
    • 將數據框從寬格式轉換為長格式是所有 seaborn plots的標准,而不僅僅是所示示例。
  • python 3.8.12pandas 1.3.4matplotlib 3.4.3seaborn 0.11.2

示例數據框

import pandas as pd
import seaborn as sns

df = pd.DataFrame({'X_Axis':[1,3,5,7,10,20],
                   'col_2':[.4,.5,.4,.5,.5,.4],
                   'col_3':[.7,.8,.9,.4,.2,.3],
                   'col_4':[.1,.3,.5,.7,.1,.0],
                   'col_5':[.5,.3,.6,.9,.2,.4]})

# display(df)
   X_Axis  col_2  col_3  col_4  col_5
0       1    0.4    0.7    0.1    0.5
1       3    0.5    0.8    0.3    0.3
2       5    0.4    0.9    0.5    0.6
3       7    0.5    0.4    0.7    0.9
4      10    0.5    0.2    0.1    0.2
5      20    0.4    0.3    0.0    0.4

# convert to long (tidy) form
dfm = df.melt('X_Axis', var_name='cols', value_name='vals')

# display(dfm.head())
   X_Axis   cols  vals
0       1  col_2   0.4
1       3  col_2   0.5
2       5  col_2   0.4
3       7  col_2   0.5
4      10  col_2   0.5

當前繪圖方法

catplot圖:圖形級

使用帶有kind=seaborn.catplot (例如kind='point'以重現FactorPlot默認值):

g = sns.catplot(x="X_Axis", y="vals", hue='cols', data=dfm, kind='point')

在此處輸入圖像描述

pointplot :軸級

sns.pointplot(x="X_Axis", y="vals", hue='cols', data=dfm)

在此處輸入圖像描述

原來的

factorplot :更名為catplot v0.9.0(2018 年 7 月)

新版本的 seaborn 收到警告:

factorplot函數已重命名為catplot 原始名稱將在未來的版本中刪除。 請更新您的代碼。 請注意, factorplot ( 'point' ) 中的默認kind已更改catplot'strip'

g = sns.factorplot(x="X_Axis", y="vals", hue='cols', data=dfm)

# using pd.melt instead of pd.DataFrame.melt for pandas < 0.20.0
# dfm = pd.melt(df, 'X_Axis', var_name='cols',  value_name='vals')
# g = sns.factorplot(x="X_Axis", y="vals", hue='cols', data=dfm)

圖形

除了強大的@jezrael 對於那些來自谷歌的人之外,如果你打算用原始數據框的索引繪制線條,只需執行以下操作:

df = pd.DataFrame({'col_2':[.4,.5,.4,.5,.5,.4],
                   'col_3':[.7,.8,.9,.4,.2,.3],
                   'col_4':[.1,.3,.5,.7,.1,.0],
                   'col_5':[.5,.3,.6,.9,.2,.4]})

# resetting index before melting to save the current index in 'index' column...
df = df.reset_index().melt('index', var_name='cols',  value_name='vals')
g = sns.catplot(x="index", y="vals", hue='cols', data=df, kind='point')

暫無
暫無

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

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