1

I am building my own legend for a complicated figure where some lines have a hexadecimal color (e.g. #009933). To build the legend I have a column 'color' that has the same hexadecimal color as the line in the plot. I apply the color to the background of the color cell using the pandas apply function, as shown below.

import pandas as pd

def legend_styling(val):
    if val.name == 'color':
        return ['background-color: %s'%x for x in val]
    elif val.name == 'shift':
        return ['font-weight: bold' for x in val]

df = pd.DataFrame({
    'form': {1: 'C4H6O5', 2: 'C4H6O5', 3: 'C4H4O4', 4: 'C4H5N3O'}, 
    'name': {1: 'Malate', 2: '3-Dehydro-L-threonate', 3: 'Fumarate', 4: 'Cytosine'}, 
    'color': {1: '#009933', 2: '#009933', 3: '#e67300', 4: '#e63900'},
    'shift': {1: 'm+0', 2: 'm+0', 3: 'm+0', 4: 'm+0'}
})
df.style.apply(legend_styling, axis=0,subset=['color','shift'])

output

I would like to color the text (the black hex codes) in the 'color' column the same as the background so that they blend away. I somehow need to apply both of the following CSS styling options to the cell 'background-color: #xxxxxx' and 'color: #xxxxxx'. Is there a way of doing this?

1 Answer 1

1

Not sure if you were able to resolve this, but I thought I would share my solution for anyone who might chance upon this page. I like to take a more readable approach when applying styles:

def style_conditions(x):
    bg_color_na = '#d9d9d9'
    bg_color_1 = '#ff0000'
    bg_color_2 = '#ffc000'
    bg_color_3 = '#ffff00'
    bg_color_4 = '#00b0f0'
    color_1 = '#ffffff'
    
    
    if x == 'Not Inspected':
        return  f'background-color: {bg_color_na}'
    elif x == '1-Urgent Repair':
        return  f'background-color: {bg_color_1}; color: {color_1}'
    elif x == '2-Repair Within a Week':
        return  f'background-color: {bg_color_2}'
    elif x == '3-Repair Next Opportunity':
        return  f'background-color: {bg_color_3}'
    elif x == '4-Scheduled Repair':
        return  f'background-color: {bg_color_4}'
    else:
        return ''

df.style.applymap(style_conditions)

Here note x == '1-Urgent Repair' gets two styles:

  1. One for 'background-color' to shade the cell
  2. One for 'color' to change the text color to white.

So, to answer your question more directly, to apply multiple styles just separate by semi-colon.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.