chachacha
chachacha

Reputation: 338

Color coding numbers in Python similar to Excel conditional formatting

Is there a module or any workarounds in Python to color code numbers from 0 to 100 going from red to green? I'm trying to better visualize a score by changing the font color based on the number but don't want to reinvent the wheel. Thought I could find myself 100 different colors and make a dictionary out of it but wanted to ask the community in advance. Many thanks.

NOTE: I am using Python, Flask, and HTML. I need a simple function/module that I can plug a number into to output a corresponding color in hex.

Upvotes: 2

Views: 1526

Answers (3)

mysl
mysl

Reputation: 1053

Perhaps try to separate the colors into 10 buckets instead of 100, then make a list out of it.

colors = ["#first", "#second", "#third", ..., "#tenth"]

Then, write a simple function to assign the number to the corresponding color.

def pick_color(num):
    if num in range(0, 10):
        return colors[1]
    elif num in range(10, 20):
        return colors[2]

...and so on.

Upvotes: 1

Heini
Heini

Reputation: 295

Everything you need for this can be found in the matplotlib.

https://matplotlib.org/2.0.0/examples/color/named_colors.html

Upvotes: 1

Nicolas Gervais
Nicolas Gervais

Reputation: 36684

In Pandas, you can use the following code to get the picture attached. You will need Pandas, Numpy for rounding, and you may need Matplotlib as well.

(np.round(df.corr().iloc[:-1, :], 6).style.format({}) .background_gradient(cmap='RdYlGn', low=.4, high=.4))

enter image description here

Upvotes: 1

Related Questions