2

I used plot_ly to visualize my data as sunburst as done before with Adobe Illustrator, however failed to colour the segments likewise.

Here is the code (colour codes are random):

library(plotly)
tab <- data.frame(
  labels = c("Total", "Planerlöse", "Abgeltung", "Bund", "Kanton Thurgau", "Kanton Thurgau Netto", "Gemeinden" ),
  parents = c("", "Total", "Total", "Abgeltung", "Abgeltung", "Kanton Thurgau", "Kanton Thurgau"),
  values = c(100, 46,54, 23.76, 30.24, 20.26, 9.97),
  colors=c("#f28f1c", "#fef4e8", "#2771b0", "#e9f1f7",
           "#b5b5b5", "#787878", "#333333"),
  type = 'sunburst',
  branchvalues = 'total'
)

fig <- plot_ly(tab, labels = ~labels, parents = ~parents, 
                      values = ~values, colors=colors, type = 'sunburst', branchvalues = 'total'
)

fig

And here the original plot I'd like to replicate: enter image description here

Thanks for any advise and help!

  • This seems to be a duplicate of [this](https://stackoverflow.com/questions/61130745/plotly-sunburst-coloring). Have you tried this solution, `p |> layout(colorway = ~colors)` and found it doesn't work? – SamR Aug 07 '23 at 12:15
  • Thanks, see my comment above, this does not solve the question of coloring each segment in a different color, I've already tried this...any other idea? Thank you! – user11841097 Aug 07 '23 at 12:21

2 Answers2

0

You could add a layout using colorway to add the colors to your sunburst plot like this:

library(plotly)
library(dplyr)

fig <- plot_ly(tab, labels = ~labels, parents = ~parents, 
               values = ~values, type = 'sunburst', branchvalues = 'total'
) %>% layout(colorway = ~colors)

fig

Created on 2023-08-07 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • Thank you for the hint, I tried that. But how do I need to change the color list so that each segment appears in a different color? – user11841097 Aug 07 '23 at 12:19
0

I think the key here is to realise that, somewhat surprisingly, the arcs in a sunburst plot are considered to be markers in the same way as a point in a scatter plot. This means we can style them in the way described in the plotly marker style docs. For example:

# Define marker
marker <- list(
    colors = ~colors,
    line = list(
        color = "black",
        width = 2
    )
)

plot_ly(
    tab,
    labels = ~labels,
    parents = ~parents,
    values = ~values,
    type = "sunburst",
    branchvalues = "total",
    marker = marker # pass the marker here
)

enter image description here

SamR
  • 8,826
  • 3
  • 11
  • 33