【问题标题】:Python Dash Plotly : Flip/reverse colour legend when formatting tablePython Dash Plotly:格式化表格时翻转/反转颜色图例
【发布时间】:2021-10-27 13:40:22
【问题描述】:

我想根据值从高(红色颜色)到小(绿色颜色)按值对列进行着色。

但是,通过使用带有默认“RdYlGn”的以下代码,我只能以相反的方式执行此操作,例如:

def discrete_background_color_bins(df, n_bins=7, columns='all'):

 bounds = [i * (1.0 / n_bins) for i in range(n_bins+1)]
 if columns == 'all':
     if 'id' in df:
         df_numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
     else:
         df_numeric_columns = df.select_dtypes('number')
 else:
     df_numeric_columns = df[columns]
 df_max = df_numeric_columns.max().max()
 df_min = df_numeric_columns.min().min()
 ranges = [
     ((df_max - df_min) * i) + df_min
     for i in bounds
 ]
 styles = []
 legend = []
 for i in range(1, len(bounds)):
     min_bound = ranges[i - 1]
     max_bound = ranges[i]
     backgroundColor = colorlover.scales[str(n_bins+4)]['div']['RdYlGn'][2:-2][i - 1]
     color = 'black'

     for column in df_numeric_columns:
         styles.append({
             'if': {
                 'filter_query': (
                     '{{{column}}} >= {min_bound}' +
                     (' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
                 ).format(column=column, min_bound=min_bound, max_bound=max_bound),
                 'column_id': column
             },
             'backgroundColor': backgroundColor,
             'color': color
         })
     legend.append(
         html.Div(style={'display': 'inline-block', 'width': '60px'}, children=[
             html.Div(
                 style={
                     'backgroundColor': backgroundColor,
                     'borderLeft': '1px rgb(50, 50, 50) solid',
                     'height': '10px'
                 }
             ),
             html.Small(round(min_bound, 2), style={'paddingLeft': '2px'})
         ])
     )

 return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))

谁能告诉我如何突出红色中的高值和绿色(或蓝色)中的小值?

谢谢。

【问题讨论】:

    标签: python colors plotly plotly-dash plotly-python


    【解决方案1】:

    一个简单的解决方案是反转颜色列表。

    所以不要这样:

    backgroundColor = colorlover.scales[str(n_bins+4)]['div']['RdYlGn'][2:-2][i - 1]
    

    你可以这样做:

    backgroundColor = colorlover.scales[str(n_bins+4)]['div']['RdYlGn'][::-1][2:-2][i - 1]
    

    【讨论】:

    • 感谢@Bas van der Linden!它就像一个魅力!我还尝试了一些其他色标,例如“YlOrRd”和“Jet”,但我得到了 KeyError 。你知道为什么吗?谢谢。
    • @FlyUFalcon 'YlOrRd' 色标似乎不是'div' 的一部分,而是'seq' 的一部分。见源代码here'Jet' is a plotly colorscale,但似乎不是 colorlover 色标。
    • 我不知道为什么 'Jet' 和其他一些色标是 plotly 的一部分,而不是 colorlover 的一部分,但是如果提供的比例没有,您可以轻松使用您唯一的 rgb 颜色列表不要剪它。例如:colorlover.scales['3']['seq']['YlOrRd'] = ['rgb(255,237,160)', 'rgb(254,178,76)', 'rgb(240,59,32)']
    • 谢谢。我还没有弄清楚如何自定义颜色图例。你介意看看我的最新问题stackoverflow.com/questions/69004814/… 吗?非常感谢。
    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多