简体   繁体   中英

Setting cell color of matplotlib table and save as a figure?

I'm following this code a link ! to save a table as the image, and I have some feature like check value in a cell then set color for a cell, but I added some code stylemap, it doesn't work

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



df = pd.DataFrame()
df['date'] = ['2016-04-01', '2016-04-02', '2016-04-03']
df['calories'] = [2200, 2100, 1500]
df['sleep hours'] = [2200, 2100, 1500]
df['gym'] = [True, False, False]
df.style.applymap(color)
render_mpl_table(df, header_columns=0, col_width=2.0)

.......
def color(val):
    if val < datetime.now():
        color = 'green'
    elif val > datetime.now():
        color = 'yellow'
    elif val > (datetime.now() + timedelta(days=60)):
        color = 'red'
    return 'background-color: %s' % color

def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,
                 header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
                 bbox=[0, 0, 1, 1], header_columns=0,
                 ax=None, **kwargs):
if ax is None:
    size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])
    fig, ax = plt.subplots(figsize=size)
    ax.axis('off')

mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)

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

for k, cell in six.iteritems(mpl_table._cells):
    cell.set_edgecolor(edge_color)
    if k[0] == 0 or k[1] < header_columns:
        cell.set_text_props(weight='bold', color='w')
        cell.set_facecolor(header_color)
    else:
        cell.set_facecolor(row_colors[k[0]%len(row_colors) ])
return ax

I put style under dataframe then render Table

My solution is create new dataframe for Cell Colors, create the dataFrame with colors checked those values in table, then add to cellColours My code block:

#table datas
df = pd.DataFrame()
members = [x.display_name[:10] for x in message.server.members]
arrayDataFrame(members, 'Players', df)
arrayDataFrame(Data=members, df=df)
#table Colors
cf = pd.DataFrame()
arrayColorFrame(members, "Players", cf)
arrayColorFrame(Data=members, df=cf)
#render
plt = render_mpl_table(df, header_columns=0, col_width=2.0, CellCol= cf)

>>>>>>>>>>>>>>
def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,
                 header_color='#40466e', row_colors=['#f1f1f2', 'W'], edge_color='B',
                 bbox=[0, 0, 1, 1], header_columns=0,
                 ax=None, CellCol=None, **kwargs):
>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>
      mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns,
            cellColours=CellCol.values, **kwargs)


def arrayDataFrame(Data, Lable='No', df=None):
    if df is None:
        df = pd.DataFrame()
    leng = len(Data)
    array = list()
    if Lable == 'No':
        for index in range(leng):
            array.append(int(index + 1))
    else:
        for val in Data:
            array.append(val)
    df[Lable] = array
    return df

def arrayColorFrame(Data, Lable='No', df=None):
    if df is None:
        df = pd.DataFrame()
    leng = len(Data)
    array = list()
    if Lable == 'No':
        for index in range(leng):
            val = index + 1
            if val < 10:
                color = 'green'
            elif val < 20:
                color = 'yellow'
            elif val < 40:
                color = 'red'
            else:
                color = 'w'
            array.append(color)
    else:
        for val in Data:
            if "nat" in val :
                color = 'blue'
            else:
                color='w'
            array.append(color)
    df[Lable] = array
    return df

Result testing in discord python : Picture

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM