Victor Mayrink
Victor Mayrink

Reputation: 1151

Plotly: Bar and pie charts side by side

I would like to plot a bar and a pie chart side by side using the subplot function in the plotly package in R. However, a big pie chart is plotted in the center of the graph, overlaying the bar plot.

Here is a sample code:

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

bar <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar') %>%
  layout(yaxis = list(title = 'Count'), barmode = 'stack')

pie <- plot_ly(data, labels = ~Animals, values = ~LA_Zoo, type = 'pie', hole = 0.6)

subplot(bar, pie)

enter image description here

How can I fix it?

Upvotes: 5

Views: 2934

Answers (1)

Prem
Prem

Reputation: 11955

Let's try this -

library(plotly)

#sample data
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

#plot
plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar') %>%
  layout(yaxis = list(title = 'Count'), xaxis = list(domain = c(0, 0.5)), barmode = 'stack') %>%
  add_trace(data, labels = ~Animals, values = ~LA_Zoo, type = 'pie', hole = 0.6,
            domain = list(x = c(0.5, 1)))

Upvotes: 2

Related Questions