Cabbage Head
Cabbage Head

Reputation: 21

Changing plotlys hovertip text color

I am running the code snippet displaying qualitative swatches from the documentation on discrete colors.

import plotly.express as px

fig = px.colors.qualitative.swatches()
fig.show()

How to I change the hovertip text to white? I find some of the backgrounds dont have good contrast with the text.

example

Upvotes: 2

Views: 2101

Answers (2)

Doyousketch2
Doyousketch2

Reputation: 2145

To retain hover background, and ability to read all entries - e.g. you won't struggle to read white text on pastel swatches.

#! /usr/bin/python3
##  pip3 install numpy pandas plotly
import plotly.express as px

fig = px .colors .qualitative .swatches()

for item in fig['data']:
    ##  print( type(item), '\n', item, '\n' )

    font_colors = []
    for data_entry in range(  len( item['customdata'] )  ):
        colorstring = item['marker']['color'][data_entry]

        if colorstring .startswith('#'):
            ##  print( colorstring )  ##  #336699
            rr = int( colorstring[1:3], 16 )  ##  0x33
            gg = int( colorstring[3:5], 16 )  ##  0x66
            bb = int( colorstring[5:], 16 )  ##  0x99
        else:
            ##  print( colorstring[4:-1] )  ##  rgb(33, 66, 99)
            rrggbb = colorstring[4:-1] .replace(' ', '' ) .split(',')

            rr = int( rrggbb[0] )  ##  33
            gg = int( rrggbb[1] )  ##  66
            bb = int( rrggbb[2] )  ##  99

        ##  stackoverflow.com/questions/596216/formula-to-determine-perceived-brightness-of-rgb-color
        if rr+rr+rr +gg+gg+gg+gg +bb > 255 *3:  ##  increase contrast
            rr, gg, bb = 0, 0, 0
        else:
            rr, gg, bb = 255, 255, 255

        hovercolor = f"rgb( {rr}, {gg}, {bb} )"
        font_colors .append( hovercolor )

    item['hoverlabel'] = dict( font_color=font_colors )

fig.show()

https://plotly.com/python/hover-text-and-formatting/
https://plotly.com/python/creating-and-updating-figures/

Upvotes: 0

AS11
AS11

Reputation: 1471

You can either change the text color or you can change the background color of the hover text. The way to do this can be found here (plolty documentation for formatting hover text).

For changing the color of the font, you can add this line of code to your current code:

fig.update_layout(
hoverlabel=dict(
    font_color="white",
))

This gives a result that looks like this:

enter image description here

For changing the background color of the hover text, you can simply add this line to your code:

fig.update_layout(
    hoverlabel=dict(
        bgcolor="white",
    ))

This gives a result that looks like this: enter image description here

Upvotes: 3

Related Questions