Search code examples
rplotly

Trouble with creating bar & pie subplot with R plotly


I've created a Plotly bar and pie chart and want to combine them to form one chart.

When I use subplot() to combine these Plotly charts, the pie & bar charts overlap.

Any advice on how to present these plots so that each is in its own row? Thank you.

Here's a picture of what I'm currently experiencing: enter image description here

Reprex below:

#Pie chart example
pie_tibble <- tibble(donuts = c(49050, 66924),
                    group = c("Group A", "Group B"))

pie <- plot_ly(data = pie_tibble, labels = ~group, values = ~donuts, type = 'pie',
               showlegend = F,
               hoverinfo = "none",
               marker = ~list(colors = c('#404040', '#24608B'))) %>% 
  layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))


bar_tibble <- tibble(category = c("Cat 1", "Cat 1", "Cat 2", "Cat 2"),
                     pct_increase = c(0.17, 0.25, 0.64, 0.85),
                     week = c(1, 2, 1, 2)) 

#Bar chart example
bar <- plot_ly(data = bar_tibble, hoverinfo = "none") %>%
  
  layout(
    barmode = 'stack',
    showlegend = F) %>%
  
  add_trace(
    x = ~pct_increase,
    y = ~category,
    type = "bar",
    transforms = list(
      list(
        type = "aggregate",
        groups = ~category,
        aggregations = list(
          list(
            target = "x", func = "avg", enabled = T)))))
 
#Combine charts
subplot(bar, pie, nrows = 2)

Solution

  • Pie charts and plotly::subplot() are notoriously challenging - though you can get around many of the issues by specifying the domain manually. Below I have changed the pie code by specifying the domain = list(...) as so:

    pie <- plot_ly(data = pie_tibble, labels = ~group, values = ~donuts, type = 'pie',
                   # Specify the domain here
                   domain = list(x = c(0.5, 0.5), # centered on x axis
                                 y = c(0.0, 0.4)),
                   showlegend = F,
                   hoverinfo = "none",
                   marker = ~list(colors = c('#404040', '#24608B'))) %>% 
       layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
             yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
    

    subplot(bar, pie, nrows = 2) now gives:

    enter image description here

    Sorry I don't have a more elegant answer, but hoping someone else might!