单独绘制plotly.graph_objects.Bar的颜色刻度 [英] Individually color ticks of a plotly.graph_objects.Bar

查看:146
本文介绍了单独绘制plotly.graph_objects.Bar的颜色刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

以下是 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} {倒入粉/nuit} $","$ \\ color {blue} {doux} $'] 

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

 将dash_core_components导入为dcc将dash_html_components导入为html从dash.dependencies导入输入,输出导入plotly.graph_objs将熊猫作为pd导入从os.path导入abspath,dirname,加入应用=破折号(__name__)def get_color(颜色,文字):s ='$ \ color {'+ str(color)+'} {'+ str(text)+'} $'返回sdf = pd.read_csv('some_file.csv')def layout():返回html.Div([dcc.Dropdown(id ='perfume-dropdown',options = [{'label':x,'value':x} for df.index.unique()中的x,值=我的巴宝莉-香水"),html.Div(id ='dd-output-container'),html.Div([dcc.Graph(id ='graph-attributes')])])@ app.callback(输出(component_id ='graph-attributes',component_property ='figure'),[输入(component_id ="perfume-dropdown",component_property ="value"))])def update_graph(my_dropdown):dfc = df.sort_values(by ='perceived_benefit',ascending = True)痕迹= []刻度= []颜色= []对于范围内的我(len(dfc)):如果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] +'感知到的,方向='h')滴答= dfc.iloc [i] .values [0]如果dfc.iloc [i] .values [1]>0:颜色=红色"别的:颜色=蓝色"ticks.append(tick)colors.append(颜色)traces.append(trace_claimed)#traces.append(trace_perceived)键= dict(zip(小记号,颜色))ticktext = [在keys.items()中为k,v获得get_color(v,k)]打印(ticktext)Figure = go.Figure(data = traces,layout = go.Layout(title ='Score des parfums sur les at les attributs',barmode ='堆栈'))Figure.update_layout(yaxis = dict(tickmode ='array',ticktext = ticktext,tickvals = ticks))返回图 

解决方案

使用

通过添加两件事:

  pip install dash_defer_js_import 

 将dash_defer_js_import导入为djimathjax_script = dji.Import(src ="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_SVG")[...]def layout():返回html.Div([dcc.Dropdown(id ='perfume-dropdown',options = [{'label':x,'value':x} for df.index.unique()中的x,值=我的巴宝莉-香水"),html.Div(id ='dd-output-container'),html.Div([dcc.Graph(id ='graph-attributes')]),mathjax_script#在此处使用脚本]) 

总共:

 将dash_core_components导入为dcc将dash_html_components导入为html从dash.dependencies导入输入,输出导入plotly.graph_objs将熊猫作为pd导入从os.path导入abspath,dirname,加入从破折号导入破折号应用=破折号(__name__)将dash_defer_js_import导入为djimathjax_script = dji.Import(src ="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_SVG")def get_color(颜色,文字):s ='$ \ color {'+ str(color)+'} {'+ str(text)+'} $'返回sdf = pd.read_csv('some_file.csv')def layout():返回html.Div([dcc.Dropdown(id ='perfume-dropdown',options = [{'label':x,'value':x} for df.index.unique()中的x,值=我的巴宝莉-香水"),html.Div(id ='dd-output-container'),html.Div([dcc.Graph(id ='graph-attributes')]),mathjax_script])@ app.callback(输出(component_id ='graph-attributes',component_property ='figure'),[输入(component_id ="perfume-dropdown",component_property ="value"))])def update_graph(my_dropdown):dfc = df.sort_values(by ='perceived',ascending = True)痕迹= []刻度= []颜色= []对于范围内的我(len(dfc)):如果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] +'感知到的,方向='h')滴答= dfc.iloc [i] .values [0]如果dfc.iloc [i] .values [1]>0:颜色='红色'别的:颜色=蓝色"ticks.append(tick)colors.append(颜色)traces.append(trace_claimed)#traces.append(trace_perceived)键= dict(zip(刻度,颜色))ticktext = [在keys.items()中为k,v获得get_color(v,k)]打印(ticktext)Figure = go.Figure(data = traces,layout = go.Layout(title ='Score des parfums sur les at les attributs',barmode ='堆栈'))Figure.update_layout(yaxis = dict(tickmode ='array',ticktext = ticktext,tickvals = ticks))返回图如果__name__ =='__main__':app.layout = layout()app.run_server(debug = True) 


没有下拉菜单的图片:

I have a multi-index dataframe dfc which I want to plot as a bar chart with the color of the tick on the yaxis depending on the value of dfc.iloc[i].values[1] for any value i.

                                                           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

In order to achieve that I tried this answer by updating the ticktext value of the yaxis property in the layout, as it seems that plotly has full LaTeX support.

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)
)

However it only produces a weird text for the ticks:

Here is the ticktext value:

['$\\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}$']

Here is a minimal reproducible example:

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

解决方案

Using the approach from here with your code, and the following some_file.csv:

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

We can achieve this (with my sample):

Through adding two things:

pip install dash_defer_js_import

and

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
    ])

All in all:

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)


Picture without a dropdown menu:

这篇关于单独绘制plotly.graph_objects.Bar的颜色刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆