通过列值对背景单元格颜色进行着色

时间:2019-09-25 03:30:03

标签: python pandas matplotlib colorize

我正在尝试将颜色映射到表格中的单元格。但是,我希望从单独的列中的值中调用它。具体来说,对于以下示例,我正在绘制Place中的时间值。但是,我有一个名为Code的单独列,它是这些时间值的参考。我希望为Code中的每个唯一值映射一个单独的颜色,以区分时间值。

目前,我正在为适当的时间值手动插入单独的颜色。我希望生成一个使用颜色映射并可以处理Code中不同值的更灵活的函数。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import six

df = pd.DataFrame({
    'Place' : ['Johnathon Santiago-Guillermo','Alan','Cory','Jim','Johnathon Santiago-Guillermo','Alan','Cory','Jim'],                                
    'Number' : ['1','3','5','6','2','4','6','7'],          
    'Code' : ['1','2','3','4','1','2','3','4'],                      
    'Time' : ['1904-01-01 08:00:00','1904-01-01 09:00:00','1904-01-02 01:00:00','1904-01-02 02:00:00','1904-01-01 08:10:00','1904-01-01 09:10:00','1904-01-02 01:10:00','1904-01-02 02:10:00'],                           
    })

df['Time'] = pd.to_datetime(df['Time'])
df = df.sort_values('Time')
df['Time'] = pd.DatetimeIndex(df['Time']).time

df1 = df.pivot_table(index = 'Number', columns = 'Place', values = 'Time', 
        aggfunc = 'first').fillna('')

df1 = df1.reindex(columns = df['Place'].unique())

fig, ax = plt.subplots(figsize = (20, 20))

def Sheet(ax1):
    ax1.axis('off')
    ax1.axis('tight')
    Times = ax1.table(cellText = df1.values, colLabels = df1.columns, cellLoc='center',
             bbox = [0,0,1,1])

    Times.auto_set_font_size(False)
    Times.set_fontsize(5)

ax1 = plt.subplot2grid((2,3), (0,0), colspan = 3)   

Sheet(ax1)

plt.show()

1 个答案:

答案 0 :(得分:1)

我稍微玩了一下您的函数,并通过了cmap='tab10'。但是首先,您可能要确保颜色代码与时间的形状相同:

new_df = df.pivot_table(index='Number', 
                        columns='Place', 
                        aggfunc='first', 
                        fill_value='')

# data
df1 = new_df['Time'].reindex(columns = df['Place'].unique())

# codes
df2 = (new_df['Code'].reindex(columns = df['Place'].unique())
           .replace('',0)
           .astype(int)
      )

现在更改功能:

def render_mpl_table(data, col_width = 1, row_height = 0.3, font_size = 6,
                     header_color='black', row_colors= 'black', edge_color='black',
                     bbox=[0, 0, 1, 1], header_columns=0,
                     cmap=None,
                     ax=None, **kwargs):

    ### blah
    ### ...
    ### here comes the change
    ### remove everything after
    # Unique values in code

    # define the cmap
    # maybe checking if the cmap is continuous or discreet
    if cmap is None: cmap='tab10'
    cm = plt.cm.get_cmap('tab10')

    # map the codes to the colors
    colours = np.array(cm.colors)[df2.values]

    # Set face colour of cell based on value in Code
    for c, cell in mpl_table._cells.items():
        if  (c[0]==0                           # header
            or c[1] == -1                      # index
            or df2.values[c[0]-1, c[1]]==0):   # 0 - code or empty cell

            continue

        cell.set_facecolor(colours[c[0]-1, c[1]])

    mpl_table.auto_set_font_size(False)
    mpl_table.set_fontsize(font_size)   

输出

enter image description here