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

2024/10/11 0:29:18

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' % colordef 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

Answer

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] = arrayreturn dfdef 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 + 1if 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] = arrayreturn df

Result testing in discord python : Picture

https://en.xdnf.cn/q/118393.html

Related Q&A

Errno 111 Connection refused - Python Mininet API hosts client/server no connection?

I am new to Mininet and I am trying to find a way to use a script in python to execute a few tests using Mininet. More precisely I want to build topology and send a few xmlrpc request from one host t…

Finding the Corners of the an array of coordinates

I have a 2D array of Coordinates in Numpy.My goal is to attempt to find the corners (as if it were a square). So the :Top left: smallest x, highest y Top right: largest x, largest y bottom left: smalle…

How to make a dictionary retain its sort order?

def positive(self):total = {}final = {}for word in envir:for i in self.lst:if word in i:if word in total:total[word] += 1else:total[word] = 1final = sorted(total, reverse = True)return totalThis return…

Counting line frequencies and producing output files

With a textfile like this:a;b b;a c;d d;c e;a f;g h;b b;f b;f c;g a;b d;fHow can one read it, and produce two output text files: one keeping only the lines representing the most often occurring couple …

Check if parent dict is not empty and retrieve the value of the nested dict

Lets suppose that I have a nested dictionary which looks like that:parent_dict = { parent_key: {child_key: child_value}How can I write the following code:if parent_dict.get(parent_key) is not None and …

List combinations in defined range

I am writing parallel rainbow tables generator using parallel python and multiple machines. So far, I have it working on a single machine. It creates all possible passwords, hashes them, saves to file.…

Python turtle drawing a symbol

import turtlewin=turtle.Screen()t = turtle.Turtle() t.width(5)#The vertical and horizontal lines t.left(90) t.forward(70) t.left(90) t.forward(20)t.left(90) t.forward(60) t.left(120) t.forward(35) t.b…

Display a countdown for the python sleep function in discord embed in python

hi all I am doing one discord bot I need to send one countdown its like a cooldown embed after every request I did this code but I dont know how to add this in my embedfor i in range(60,0,-1):print(f&q…

Bypass rate limit for requests.get

I want to constantly scrape a website - once every 3-5 seconds withrequests.get(http://www.example.com, headers=headers2, timeout=35).json()But the example website has a rate limit and I want to bypass…

ValueError when using if commands in function

Im creating some functions that I can call use keywords to call out specific functions,import scipy.integrate as integrate import numpy as npdef HubbleParam(a, model = "None"):if model == &qu…