Home > Back-end >  How to color strings with seaborn?
How to color strings with seaborn?

Time:10-02

I have a data of strings (letters) in excel file and I'm looking a way to show it more visual atractive.

I like seaborn coloring cells, I was wondering can I do that. I have 6 values, (a,b,c,d,e,f).

Like this and to be part of gradient of same color.

enter image description here

CodePudding user response:

You can't use continuous colors for discrete values as it. You have to pick colors along the palette. Create a dict of unique letters as key and color as value.

import pandas as pd
import numpy as np
import seaborn as sns

data = {'data1': ['a', 'b', 'a', 'c', 'c', 'c', 'e', 'a', 'e'],
        'data2': ['c', 'd', 'b', 'b', 'd', 'c', 'c', 'f', 'd'],
        'data3': ['a', 'a', 'd', 'b', 'e', 'a', 'e', 'c', 'a']}
df = pd.DataFrame(data)

values = np.unique(np.ravel(df)).tolist()
colors = dict(zip(values, sns.color_palette('flare', len(values)).as_hex()))

df.style.applymap(lambda v: f"background-color: {colors[v]}; color: white") \
        .to_excel('data.xlsx')

background-color

Update

Is it possible to restrict for just two columns, like data1 and data3?

def highlight_column(col):
    if col.name in ['data1', 'data3']:
        return [f"background-color: {colors[v]}; color: white" for v in col.values]

df.style.apply(highlight_column).to_excel('data.xlsx')

enter image description here

  • Related