【问题标题】:Assign Color Using Seaborn Based on Column Name根据列名使用 Seaborn 分配颜色
【发布时间】:2019-11-08 13:48:31
【问题描述】:

我正在尝试创建 4 种类型的图来总结我的数据。我已经包含了创建 2 种图表类型的代码。我正在迭代蜡笔 seaborn 调色板以获得每个图表的独特颜色。但是,我希望数据集中每一列的颜色保持一致。

我创建了几行假数据。我的数据如下所示:

         Time  type1  type2  type3
0  2015-01-01    100    200    300
1  2015-02-01    150    250    350
2  2015-03-01    300    300    300
3  2015-04-01    350    350    350

代码:

#Setting up data 
import warnings
import itertools
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
import sys
import seaborn as sns 

data = [{'Time': '201501','type1': 100, 'type2': 200, 'type3':300}, 
        {'Time': '201502' ,'type1':150, 'type2': 250, 'type3': 350}, 
        {'Time': '201503' ,'type1':300, 'type2': 300, 'type3': 300}, 
        {'Time': '201504' ,'type1':350, 'type2': 350, 'type3': 350}] 

data = pd.DataFrame(data) 

#Data prep

#setting index
data['Time']=pd.to_datetime(data['Time'], format='%Y%m')
data.set_index(['Time'], inplace=True)
#setting type for line graph
data=data.astype(float)

data

palette = itertools.cycle(sns.color_palette(palette=sns.colors.crayons))



############################# LINE PLOT ##################################################   

#this loops over each column in my data set and produces a graph

for i in data:  # Loop over all columns except 'Location'
    sns.set() #defaults the background
    fig, ax = plt.subplots()
    sns.set(style="ticks") 
    sns.lineplot(x=data.index,y=i,data=data,color=next(palette))  # column is chosen here
    sns.despine(offset=10, trim=True) 
    fig.set_size_inches(18,12)
    ax.set_title('{} History'.format(i), fontweight='bold')

    plt.savefig('{}.pdf'.format(i), bbox_inches='tight')  #sets file name based on column name


############################# VIOLIN PLOT ###############################################         
for i in data:  # Loop over all columns 
    sns.set() #defaults the background
    fig, ax = plt.subplots()
    sns.set(style="ticks") #darkens grid lines
    sns.violinplot(y=i, data=data,color=next(palette))  #sets which column to use
    sns.despine(offset=10, trim=True) 
    fig.set_size_inches(18,12)
    ax.set_title('{} Violin Plot'.format(i), fontweight='bold') #sets chart title based on column
    plt.savefig('{}_violin.pdf'.format(i), bbox_inches='tight')  #sets file name based on column name

运行代码时,每个图表都有唯一的颜色,但类型 1 的折线图和小提琴图的颜色不同。我希望每个图表的列之间的颜色保持一致。

【问题讨论】:

    标签: python pandas dataframe colors seaborn


    【解决方案1】:

    正在从infinitely cycling 调色板中选择颜色:

    palette = itertools.cycle(sns.color_palette(palette=sns.colors.crayons))
    sns.lineplot(..., color=next(palette)) 
    ...
    sns.violinplot(..., color=next(palette))  
    

    每次调用next(palette),都会返回循环中的下一个颜色。 因此,线图和小提琴图之间没有颜色协调(除非 奇迹般的巧合或设计,len(data.columns) 恰好是 len(sns.colors.crayons) 的倍数)。

    使线图和小提琴图颜色协调的一种方法是重置调色板 在每个循环之前:

    palette = sns.color_palette(palette=sns.crayon_palette(sns.colors.crayons))
    new_palette = itertools.cycle(palette)
    for i in data:  # Loop over all columns except 'Location'
        ...
        sns.lineplot(x=data.index, y=i, data=data, color=next(new_palette))
    
    ...
    
    new_palette = itertools.cycle(palette)
    for i in data:  # Loop over all columns 
        ...
        sns.violinplot(y=i, data=data, color=next(new_palette))
    

    在上面,palette 只是一个列表。 new_palette 是无限循环 迭代器。通过在每个for-loop 之前创建一个new_palettenext(new_palette) 将由 for-loops 以相同的顺序返回相同的颜色。

    或者,实现所需结果的一种更简单的方法是将两个 for 循环合并为一个,以便您可以在同一迭代中调用 lineplotvionlinplot 并将相同的颜色传递给两个函数调用。 将代码分解为函数有助于阐明代码的意图并保持代码整洁。

    import itertools
    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    
    def make_data():
        data = [{'Time': '201501', 'type1': 100, 'type2': 200, 'type3': 300},
                {'Time': '201502', 'type1': 150, 'type2': 250, 'type3': 350},
                {'Time': '201503', 'type1': 300, 'type2': 300, 'type3': 300},
                {'Time': '201504', 'type1': 350, 'type2': 350, 'type3': 350}]
    
        data = pd.DataFrame(data)
        data['Time'] = pd.to_datetime(data['Time'], format='%Y%m')
        data.set_index(['Time'], inplace=True)
        data = data.astype(float)
        return data
    
    def make_lineplot(data, i, color):
        fig, ax = plt.subplots()
        sns.set(style="ticks")
        sns.lineplot(x=data.index, y=i, data=data, color=color)  
        sns.despine(offset=10, trim=True)
        fig.set_size_inches(18, 12)
        ax.set_title('{} History'.format(i), fontweight='bold')
        plt.savefig('{}.pdf'.format(i), bbox_inches='tight')
    
    def make_violinplot(data, i, color):
        fig, ax = plt.subplots()
        sns.set(style="ticks")  
        sns.violinplot(y=i, data=data, color=color)  
        sns.despine(offset=10, trim=True)
        fig.set_size_inches(18, 12)
        ax.set_title('{} Violin Plot'.format(i), fontweight='bold')
        plt.savefig('{}_violin.pdf'.format(i), bbox_inches='tight')
    
    data = make_data()
    
    
    palette = itertools.cycle(sns.color_palette(palette=sns.colors.crayons))
    # I had to use the line below to get the code to run
    # palette = itertools.cycle(sns.color_palette(palette=sns.crayon_palette(sns.colors.crayons)))
    
    for i, color in zip(data, palette):  
        make_lineplot(data, i, color)
        make_violinplot(data, i, color)
    

    【讨论】:

    • 哇。谢谢你这么详细的回答!这两个选项都很棒并且解释得很好。
    【解决方案2】:

    问题出现是因为您在每次通话中都继续使用color=next(palette)。您正在寻找的是列名和颜色之间的常量映射。代码中所需的最小更改是:

    ...
    palette = itertools.cycle(sns.crayon_palette(sns.colors.crayons))  # I get an exception for your version, but I guess this is equivalent to what you meant
    
    palette = dict(zip(data.columns, palette)) # this creates a mapping between columns and colors
    
    ...
    for i in data: 
        ...
        sns.lineplot(x=data.index, y=i, data=data, color=palette[i])
        ...
    

    这样,每次绘制线条时,使用的颜色对应于特定列,而不是从迭代器的 next 函数中连续绘制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-22
      • 2016-05-18
      • 2021-03-28
      • 2020-12-03
      • 2020-06-23
      • 2019-12-18
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多