更改plotlys悬停提示文本颜色

2024-09-24 02:13:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行显示来自documentation on discrete colors的定性样例的代码片段

import plotly.express as px

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

如何将悬停提示文本更改为白色? 我发现一些背景与课文的对比度不好

example


Tags: 代码importondocumentationasfigplotlycolors
2条回答

要保留悬停背景,读取所有条目的能力-,例如,您不必费劲读取彩色样本上的白色文本

#! /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/

可以更改文本颜色,也可以更改悬停文本的背景颜色。可以在here(用于格式化悬停文本的plolty文档)中找到实现这一点的方法

要更改字体的颜色,可以将此行代码添加到当前代码中:

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

这将产生如下结果:

enter image description here

要更改悬停文本的背景色,只需将以下行添加到代码中:

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

这将产生如下结果: enter image description here

相关问题 更多 >