【问题标题】:Individually color ticks of a plotly.graph_objects.Barplotly.graph_objects.Bar 的单独颜色刻度
【发布时间】:2021-04-05 04:40:59
【问题描述】:

我有一个multi-index dataframe dfc,我想将其绘制为条形图,y 轴上刻度的颜色取决于任何值 i 的 dfc.iloc[i].values[1] 的值。

                                                           Unnamed: 1  claimed_benefit  perceived_benefit
My Burberry - Eau de Parfum                           je me sens bien                0           0.000000
Her Intense - Eau de Parfum                         convient bien moi                0           0.000000
Her Intense - Eau de Parfum                          sensuelle / sexy                0           0.000000
Her Intense - Eau de Parfum                                  nettoyer                0           0.000000
Her Intense - Eau de Parfum                             haute qualite                0           0.000000
...                                                               ...              ...                ...
Mr. Burberry Indigo - Eau de Toilette  nouveau / jamais respire avant                0           0.666667

为了实现这一点,我尝试通过更新布局中yaxis 属性的ticktext 值来实现this answer,因为似乎plotly 具有完整的LaTeX 支持。

traces = []
ticks = []
colors = []
for i in range(len(dfc)):
    if dfc.iloc[i].name == my_dropdown:
        trace_claimed = go.Bar(y=[dfc.iloc[i].values[0]], x=[dfc.iloc[i].values[2]],
                               name=dfc.iloc[i].values[0] + ' Perceived', orientation='h')

        tick = dfc.iloc[i].values[0]

        if dfc.iloc[i].values[1] > 0:
            color = 'red'
        else:
            color = 'blue'

        ticks.append(tick)
        colors.append(color)
        traces.append(trace_claimed)
            # traces.append(trace_perceived)

keys = dict(zip(ticks, colors))
ticktext = [get_color(v, k) for k, v in keys.items()]


figure = go.Figure(data=traces,
                   layout=go.Layout(title='Score des parfums sur les attributs',
                                    barmode='stack')
                   )

figure.update_layout(
    yaxis=dict(tickmode='array', ticktext=ticktext, tickvals=ticks)
)

但是它只会为刻度产生一个奇怪的文本:

这是ticktext 值:

['$\\color{blue}{je me sens bien}$', '$\\color{blue}{harsh / agressif}$', '$\\color{blue}{boisé}$', '$\\color{blue}{écœurant}$', '$\\color{blue}{strength1}$', ..., '$\\color{red}{frais}$', '$\\color{blue}{pour le soir / nuit}$', '$\\color{blue}{doux}$']

这是一个最小的可重现示例:

import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
from os.path import abspath, dirname, join

app = Dash(__name__)


def get_color(color, text):
    s = '$\color{' + str(color) + '}{' + str(text) + '}$'
    return s


df = pd.read_csv('some_file.csv')


def layout():
    return html.Div([
        dcc.Dropdown(
            id='perfume-dropdown',
            options=[{'label': x, 'value': x} for x in df.index.unique()],
            value='My Burberry - Eau de Parfum'
        ),
        html.Div(id='dd-output-container'),
        html.Div([
            dcc.Graph(id='graph-attributes')
        ])
    ])

@app.callback(
    Output(component_id='graph-attributes', component_property='figure'),
    [Input(component_id="perfume-dropdown", component_property="value")]
)
def update_graph(my_dropdown):
    dfc = df.sort_values(by='perceived_benefit', ascending=True)
    traces = []
    ticks = []
    colors = []
    for i in range(len(dfc)):
        if dfc.iloc[i].name == my_dropdown:
            trace_claimed = go.Bar(y=[dfc.iloc[i].values[0]], x=[dfc.iloc[i].values[2]],
                                   name=dfc.iloc[i].values[0] + ' Perceived', orientation='h')

            tick = dfc.iloc[i].values[0]

            if dfc.iloc[i].values[1] > 0:
                color = 'red'
            else:
                color = 'blue'

            ticks.append(tick)
            colors.append(color)
            traces.append(trace_claimed)
                # traces.append(trace_perceived)

    keys = dict(zip(ticks, colors))
    ticktext = [get_color(v, k) for k, v in keys.items()]

    print(ticktext)

    figure = go.Figure(data=traces,
                       layout=go.Layout(title='Score des parfums sur les attributs',
                                        barmode='stack')
                       )

    figure.update_layout(
        yaxis=dict(tickmode='array', ticktext=ticktext, tickvals=ticks)
    )

    return figure

【问题讨论】:

  • 很抱歉,您的最小示例无法运行。您能否提供一些来自some_file.csv 的格式化行并包含运行该示例所需的所有代码?因为如果我只使用plotly.graph_obs 并重组你的My Burberry... sn-p 它就可以完美地工作。
  • 经过一番调查,似乎Dash不支持LaTex see,但这是一个长期要求的功能
  • @Albo 该死!所以 plotly 可以,但 Dash 不支持 Latex ?
  • 找到了一个解决方案,即使Dash 本身不支持它...见下文。但似乎是的,plotly 确实支持开箱即用的LaTex,而Dash不支持

标签: python-3.x colors plotly bar-chart ticker


【解决方案1】:

here 中的方法与您的代码以及以下some_file.csv 一起使用:

name,claimed,perceived
A,0,1
B,1,2
C,0,3
D,1,4

我们可以实现这一点(使用我的示例):

通过添加两件事:

pip install dash_defer_js_import

import dash_defer_js_import as dji
mathjax_script = dji.Import(src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_SVG")

[...]

def layout():
    return html.Div([
        dcc.Dropdown(
            id='perfume-dropdown',
            options=[{'label': x, 'value': x} for x in df.index.unique()],
            value='My Burberry - Eau de Parfum'
        ),
        html.Div(id='dd-output-container'),
        html.Div([
            dcc.Graph(id='graph-attributes')
        ]),
        mathjax_script # use the script here
    ])

总而言之:

import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
from os.path import abspath, dirname, join
from dash import Dash

app = Dash(__name__)

import dash_defer_js_import as dji
mathjax_script = dji.Import(src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_SVG")

def get_color(color, text):
    s = '$\color{' + str(color) + '}{' + str(text) + '}$'
    return s


df = pd.read_csv('some_file.csv')


def layout():
    return html.Div([
        dcc.Dropdown(
            id='perfume-dropdown',
            options=[{'label': x, 'value': x} for x in df.index.unique()],
            value='My Burberry - Eau de Parfum'
        ),
        html.Div(id='dd-output-container'),
        html.Div([
            dcc.Graph(id='graph-attributes')
        ]),
        mathjax_script
    ])


@app.callback(
    Output(component_id='graph-attributes', component_property='figure'),
    [Input(component_id="perfume-dropdown", component_property="value")]
)
def update_graph(my_dropdown):
    dfc = df.sort_values(by='perceived', ascending=True)
    traces = []
    ticks = []
    colors = []
    for i in range(len(dfc)):
        if dfc.iloc[i].name == my_dropdown:
            trace_claimed = go.Bar(y=[dfc.iloc[i].values[0]], x=[dfc.iloc[i].values[2]],
                                   name=dfc.iloc[i].values[0] + ' Perceived', orientation='h')

            tick = dfc.iloc[i].values[0]

            if dfc.iloc[i].values[1] > 0:
                color = 'red'
            else:
                color = 'blue'

            ticks.append(tick)
            colors.append(color)
            traces.append(trace_claimed)
            # traces.append(trace_perceived)

    keys = dict(zip(ticks, colors))
    ticktext = [get_color(v, k) for k, v in keys.items()]

    print(ticktext)

    figure = go.Figure(data=traces,
                       layout=go.Layout(title='Score des parfums sur les attributs',
                                        barmode='stack')
                       )

    figure.update_layout(
        yaxis=dict(tickmode='array', ticktext=ticktext, tickvals=ticks)
    )

    return figure


if __name__ == '__main__':
    app.layout = layout()
    app.run_server(debug=True)

没有下拉菜单的图片:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多