Search code examples
rplotplotly

Edit boxplot tooltip text (Plotly)


How can I edit native tooltip text (median, mean, lower fence, upper fence, q1, etc) from boxplot in R code?

I tried using the locale option of the config function, but I didn’t get the expected result when locale = "pt-br". The translation of the boxplot elements is not happening as expected for the Portuguese language.

Code ex:

library(plotly)
fig <- plot_ly(x = ~rnorm(50), type = "box",
               hoverinfo = 'x')
fig |> 
  config(locale = "pt-br")

enter image description here

Other example:

fig <- plot_ly(x = ~rnorm(50), type = "box")
fig |> config(locale = "pt-br")

enter image description here

Note that it works for another language/locale.

fig |> config(locale = "ja") #locale = "es"

enter image description here

enter image description here

enter image description here


Solution

  • Following on from @Kat suggestion, we've come to a good point. But how to automate this? It seems to me that the problem is different now, it involves creating code in R in order to overcome the following error (when using @Kat var):

    Erro: mistura de códigos de escape Unicode e octal/hexadecimal em uma cadeia de caracteres não é permitido

    With the help of @JosefZ, I was able to implement the tweak by including the special characters. The understanding of the adjustment can be found here.

    The code automating the new dictionary/locale, is:

    require(plotly)
    require(rprojroot)
    require(glue)
    
    lib_dir <- find_package_root_file(find.package('plotly'))
    path_js <- glue::glue("{lib_dir}/htmlwidgets/lib/plotlyjs/locales") 
    
    file.create(glue::glue("{path_js}/pt-br_alternativo.js"))
    
    # the temporary var
    code  <- 'var locale = {
      moduleType: "locale",
      name: "pt-br",
      dictionary: {
        Autoscale: "Escala autom\u00E1tica",
        "Box Select": "Sele\u00E7\u00E3o retangular",
        "Click to enter Colorscale title": "Clique para editar o t\u00EDtulo da escala de cor",
        "Click to enter Component A title": "Clique para editar o t\u00EDtulo do Componente A",
        "Click to enter Component B title": "Clique para editar o t\u00EDtulo do Componente B",
        "Click to enter Component C title": "Clique para editar o t\u00EDtulo do Componente C",
        "Click to enter Plot title": "Clique para editar o t\u00EDtulo do Grafico",
        "Click to enter X axis title": "Clique para editar o t\u00EDtulo do eixo X",
        "Click to enter Y axis title": "Clique para editar o t\u00EDtulo do eixo Y",
        "Click to enter radial axis title": "Clique para editar o t\u00EDtulo do eixo radial",
        "Compare data on hover": "Comparar dados ao pairar",
        "Double-click on legend to isolate one trace": "Duplo clique na legenda para isolar uma s\u00E9rie",
        "Double-click to zoom back out": "Duplo clique para reverter zoom",
        "Download plot as a png": "Fazer download do gr\u00E1fico como imagem (png)",
        "Download plot": "Fazer download do gr\u00E1fico",
        "Edit in Chart Studio": "Editar no Chart Studio",
        "IE only supports svg. Changing format to svg.": "IE suporta apenas svg. Alterando formato para svg",
        "Lasso Select": "Sele\u00E7\u00E3o de lasso",
        "Orbital rotation": "Rota\u00E7\u00E3o orbital",
        Pan: "Mover",
        "Produced with Plotly": "Criado com o Plotly",
        Reset: "Restaurar",
        "Reset axes": "Restaurar eixos",
        "Reset camera to default": "Restaurar c\u00E2mera para padrao",
        "Reset camera to last save": "Restaurar c\u00E2mera para ultima salva",
        "Reset view": "Restaurar vis\u00E3o",
        "Reset views": "Restaurar vis\u00F5es",
        "Show closest data on hover": "Exibir dado mais proximo ao pairar",
        "Snapshot succeeded": "Captura instant\u00E2nea completa",
        "Sorry, there was a problem downloading your snapshot!": "Desculpe, houve um problema no download de sua captura instant\u00E2nea!",
        "Taking snapshot - this may take a few seconds": "Efetuando captura instant\u00E2nea - isso pode levar alguns instantes",
        "Toggle Spike Lines": "Habilitar/desabilitar triangula\u00E7\u00E3o de linhas",
        "Toggle show closest data on hover": "Habilitar/desabilitar exibi\u00E7ao de dado mais pr\u00F3ximo ao pairar",
        "Turntable rotation": "Rota\u00E7\u00E3o de mesa",
        Zoom: "Zoom",
        "Zoom in": "Ampliar zoom",
        "Zoom out": "Reduzir zoom",
        "close:": "fechamento:",
        "high:": "alta:",
        "incoming flow count": "contagem de fluxo de entrada:",
        "kde:": "kde:",
        "lat:": "latitude:",
        "lon:": "longitude:",
        "low:": "baixa:",
        "lower fence:": "limite inferior:",
        "max:": "m\u00E1ximo:",
        "mean \u00b1 \u03c3:": "m\u00e9dia \u00b1 \u03c3:",
        "mean:": "m\u00e9dia:",
        "median:": "mediana:",
        "min:": "m\u00EDnimo:",
        "new text:": "novo texto:",
        "open:": "abertura:",
        "outgoing flow count:": "contagem de fluxo de saida:",
        "q1:": "q1:",
        "q3:": "q3:",
        "source": "origem:",
        "target::": "destino:",
        trace: "s\u00E9rie",
        "upper fence:": "limite superior:"
      },
      format: {
        days: ["Domingo", "Segunda-feira", "Ter\u00E7a-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "S\u00E1bado"],
        shortDays: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "S\u00E1b"],
        months: ["Janeiro", "Fevereiro", "Mar\u00E7o", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
        shortMonths: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"],
        date: "%d/%m/%Y"
      }
    };
    "undefined" == typeof Plotly ? (window.PlotlyLocales = window.PlotlyLocales || [], window.PlotlyLocales.push(locale)) : Plotly.register(locale);'
    
    write(code, file= glue::glue("{path_js}/pt-br_alternativo.js"))
    
    

    We use this function before creating the plot. And the result has been positive, despite the spelling errors. Other dicitionary/languages/locales that don't have this problem will certainly be able to use this solution.

    New plot:

    fig <- plot_ly(x = ~rnorm(50), type = "box")
    fig |> 
      config(locale = "pt-br_alternativo") # Attention
    

    enter image description here

    enter image description here