vendredi 30 juillet 2021

R plotly(): hovertemplate with conditional content

I have a sunburst diagram and would like to show some hoverinfo since the labels are quite long. The code is basically

fig <- plot_ly(ids=df$KtoID,
               text= df$label_5,
               labels = df$label_4,
               parents = df$parent_ID,
               values = df$value_2020,
               type = 'sunburst',
               maxdepth=2,
               insidetextorientation="horizontal",
               branchvalues = 'total',
               hovertemplate = paste('%{label}','<br>%{value} EUR<extra></extra>','<br>Anteil an %{parent}','%{percentParent: .1%}'), 
               textinfo="text")

For each element I would like to include the information about the share of parent element in %. This works fine, if I use

hovertemplate = paste('%{label}','<br>%{value} EUR<extra></extra>','<br>Anteil an %{parent}','%{percentParent: .1%}')

resulting in hoverinfo of Element with parent, that shows "Anteil an [parent] x %"

But for the root Element, since there is no parent, I get the following hoverinfor for root element "Anteil an null 100,0 %".

So for the root element I would like to just show the first part including label and value.

So far I tried an if else expression.

hovertemplate = if (any(is.na(df[,parent]))) {paste('%{label}','<br>%{value} EUR<extra></extra>')} else {paste('%{label}','<br>%{value} EUR<extra></extra>','<br>Anteil an %{parent}','%{percentParent: .1%}')},

That didn't work.

Also, I found a similar topic here, but don't know how to use it.

Does anybody have an idea, how to modify the hoverinfo like I need it?

Aucun commentaire:

Enregistrer un commentaire