user1357015 user1357015 - 1 year ago 124
R Question

R Plotly Two Plots side by side

I'm trying to get two donut plots side by side in plotly. However, I'm only getting one image. Any advice on what I'm missing?

library(dplyr)
library(plotly)

df1 <- as.data.frame(matrix(data = c("a","b", "c", 34,28, 29), nrow = 3, ncol = 2))
colnames(df1) <- c("category", "count")
df2 <- as.data.frame(matrix(data = c("Q","F", "G", 29,50, 76), nrow = 3, ncol = 2))
colnames(df2) <- c("group", "count")


p <- subplot(
plot_ly(df1, labels = category, values = count, type = "pie", hole = 0.6, showlegend = TRUE),
plot_ly(df2, labels = group, values = count, type = "pie", hole = 0.6, showlegend = TRUE),
margin = 0.05,
nrows = 2
)
p


Current Output:

enter image description here

Answer Source

You're so close. This is an adaptation of your code to Plotly's pie charts examples:

plot_ly(df1, labels = category, values = count, type = "pie", hole = 0.6, showlegend = TRUE,
        domain = list(x = c(0, 1), y = c(0.5, 1))) %>%
  add_trace(data = df2, labels = group, values = count, type = "pie", hole = 0.6, showlegend = TRUE,
            domain = list(x = c(0, 1), y = c(0, 0.5)))

side-by-side pies

(They are using add_trace instead of a parent subplot.)

If you want to add gridlines (per @Technophobe01's example), you would add

ax <- list(showline= TRUE)
plot_ly(...) %>% add_trace(...) %.%
  layout(xaxis = ax, yaxis = ax)

Many more options for it, sapmles on their axes page.