for循环,用于熊猫数据框子集的多个图

时间:2020-06-14 01:32:42

标签: python pandas seaborn

column1       column2    column3    column4   
a            1990        25         A 
b            1990        27         A 
c            1990        24         A
a            1991        26         B
b            1990        20         B
c            1990        20         C

所以column1 == a的子集应该类似于

column1       column2    column3    column4   
a            1990        25         A 
a            1991        26         B 
a            1990        20         C

我写了一段代码来生成熊猫数据框子集的多个图 子集是其中sub1的list元素中的column1值相同的行的集合

sub = ['a','b','c','d','e']

for i in sub:
    df_s = df[df['column1']==i]
    plt.figure(figsize=(5,5))
    sns.lineplot(x='column2',y='column3', data=df_s, hue='column4',legend=False)
    plt.title("Data of " + p)
plt.show

这些图与我的代码分开生成。但我只想用一个图和一个图例就可以做到。

1 个答案:

答案 0 :(得分:1)

所以我认为您需要使用FaceGrid,这是一种方法。我使用了我创建的虚假数据

sub = ['a','b','c','d','e']
#select just the sub data at once
dfs = df[df['column1'].isin(sub)]

#create the FaceGrid
g = sns.FacetGrid(dfs, 
                  col="column1", 
                  hue='column4', 
                  col_wrap=2, # here it means 2 columns depending on the position you want
                  legend_out=True) 

#lineplot each sub
g.map(sns.lineplot, 'column2', 'column3').add_legend()

#some parameters for titles, axis and legend name if you want to change them
g.set_titles("Data of {col_name}")
g.set_axis_labels(x_var="Maybe something", 
                  y_var="Something else")
g._legend.set_title('name')

#if you want to save the figure
g.savefig('test.png')

enter image description here