Edit boxplot tooltip text (Plotly)

Viewed 121

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

2 Answers

I think the easiest way to deal with this is to update your local Plotly package.

If you're worried about something going wrong with the package or if something actually did go wrong, you could reset everything you did just by running install.packages('plotly'). This updates it to the latest CRAN version. If you update Plotly for any reason, it will erase these changes.

To make the change, go to your R library (find the folder address with .Library in the R or RStudio console). For example, mine is [1] "/Library/Frameworks/R.framework/Resources/library". Go to the plotly folder -> htmlwidgets -> lib -> plotlyjs -> locales -> and open pt-br.js. (It will open with RStudio, Atom, and many other IDEs).

enter image description here

Delete everything in the file and replace it with this:

var locale = {
  moduleType: "locale",
  name: "pt-br",
  dictionary: {
    Autoscale: "Escala autom\xe1tica",
    "Box Select": "Sele\xe7\xe3o retangular",
    "Click to enter Colorscale title": "Clique para editar o t\xedtulo da escala de cor",
    "Click to enter Component A title": "Clique para editar o t\xedtulo do Componente A",
    "Click to enter Component B title": "Clique para editar o t\xedtulo do Componente B",
    "Click to enter Component C title": "Clique para editar o t\xedtulo do Componente C",
    "Click to enter Plot title": "Clique para editar o t\xedtulo do Gr\xe1fico",
    "Click to enter X axis title": "Clique para editar o t\xedtulo do eixo X",
    "Click to enter Y axis title": "Clique para editar o t\xedtulo do eixo Y",
    "Click to enter radial axis title": "Clique para editar o t\xedtulo 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\xe9rie",
    "Double-click to zoom back out": "Duplo clique para reverter zoom",
    "Download plot as a png": "Fazer download do gr\xe1fico como imagem (png)",
    "Download plot": "Fazer download do gr\xe1fico",
    "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\xe7\xe3o de la\xe7o",
    "Orbital rotation": "Rota\xe7\xe3o orbital",
    Pan: "Mover",
    "Produced with Plotly": "Criado com o Plotly",
    Reset: "Restaurar",
    "Reset axes": "Restaurar eixos",
    "Reset camera to default": "Restaurar c\xe2mera para padr\xe3o",
    "Reset camera to last save": "Restaurar c\xe2mera para \xfaltima salva",
    "Reset view": "Restaurar vis\xe3o",
    "Reset views": "Restaurar vis\xf5es",
    "Show closest data on hover": "Exibir dado mais pr\xf3ximo ao pairar",
    "Snapshot succeeded": "Captura instant\xe2nea completa",
    "Sorry, there was a problem downloading your snapshot!": "Desculpe, houve um problema no download de sua captura instant\xe2nea!",
    "Taking snapshot - this may take a few seconds": "Efetuando captura instant\xe2nea - isso pode levar alguns instantes",
    "Toggle Spike Lines": "Habilitar/desabilitar triangula\xe7\xe3o de linhas",
    "Toggle show closest data on hover": "Habilitar/desabilitar exibi\xe7\xe3o de dado mais pr\xf3ximo ao pairar",
    "Turntable rotation": "Rota\xe7\xe3o 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\xe1ximo:",
    "mean \xb1 \u03c3:": "m\xe9dia \xb1 \u03c3:",
    "mean:": "m\xe9dia:",
    "median:": "mediana:",
    "min:": "m\xednimo:",
    "new text:": "novo texto:",
    "open:": "abertura:",
    "outgoing flow count:": "contagem de fluxo de sa\xedda:",
    "q1:": "q1:",
    "q3:": "q3:",
    "source": "origem:",
    "target::": "destino:",
    trace: "s\xe9rie",
    "upper fence:": "limite superior:"
  },
  format: {
    days: ["Domingo", "Segunda-feira", "Ter\xe7a-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "S\xe1bado"],
    shortDays: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "S\xe1b"],
    months: ["Janeiro", "Fevereiro", "Mar\xe7o", "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);

You'll notice very little difference if you look closely at the JS in this answer and what's initially in the file.

After changing it locally, this is what I rendered:

enter image description here

enter image description here

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

Related