0
votes

I am trying to plot some air pollutants data using R Plotly package. So far, I am able to achieve this.

library(plotly)
val <- c(10, 12,4, 16, 8)
ap <- c("NO2", "PM10", "PM2.5", "NOx", "SO2")
plot_ly(labels = ~ap, values = ~val, type = 'pie',
        textposition = 'inside',
        textinfo = 'label')

Output

I would like to improve this pie-chart. I want to show '10' in PM10 as subscript and write "custom text" next to label. My expected outcome: PM[10] (47%) and so on. Someone care to explain how to achieve this?

1

1 Answers

1
votes

Here is an example on how to setup subscripts and custom hover text in plotly:

library(plotly)
val <- c(10, 12,4, 16, 8)
ap <- c("NO<sub>2</sub>", "PM<sub>10</sub>", "PM<sub>2.5</sub>", "NO<sub>x</sub>", "SO<sub>[2]</sub>")

For subscripts one needs to add <sub> prior and </sub> afterward the text.

Custom hovers are obtained by defining text argument in plot_ly call

plot_ly(labels = ~ap, values = ~val, type = 'pie',
        hoverinfo = 'text',
        text = ~paste0(val *100/sum(val), '%'),
        textposition = 'inside',
        textinfo = 'label')

If changing the labels was desired without the hover:

plot_ly(labels = ~paste(ap, paste0('[', val *100/sum(val), '%]')),
        values = ~val, type = 'pie',
        textposition = 'inside',
        textinfo = 'label')

enter image description here