17

I have a dataset that contains over 100 categories. If I am going to plot it, I have to write over 100 lines code for it. Here is the example from plotly official website:

library(plotly)
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)
p <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>%
add_trace(y = ~LA_Zoo, name = 'LA Zoo') %>%
layout(yaxis = list(title = 'Count'), barmode = 'stack')

As you can see, if I have over 100 zoos that are going to be plotted, I need to write add_trace for over 100 times, which is inefficient. Does anyone know of ways to simplify it? I tried using for loop but I failed.

Or if anyone know how to use ggplotly to transfer a ggplot to an interactive format, it will also solve my problem. The plot produced by ggplot is a stacked grouped bar chart which x-axis have 10 facet_grid and about 100 categories in each grid. I tried using ggplotly directly and save it as an .html, however the plot's scale is very weird. It should looks like a rectangular with width about 40 and height about 8, but in html, it just shows like a square which is unreadable.

4
  • 2
    It sounds like you need to reshape your dataset into long format. This is the closest plotly question I found, but there are many ggplot2 questions and answers on this topic.
    – aosmith
    Commented Jul 5, 2017 at 15:09
  • @aosmith Thank you ;). But this is not what I am looking for.
    – Eleanor
    Commented Jul 5, 2017 at 15:19
  • 1
    Are you saying you don't want to reshape your dataset? You might clarify your question, then, including adding the ggplot2 code that made the plot you want that you want to reproduce in plotly.
    – aosmith
    Commented Jul 5, 2017 at 15:27
  • Please show us what you are looking for. You can add screenshots.
    – Parfait
    Commented Jul 5, 2017 at 17:52

1 Answer 1

21

You can melt the data and then plot them like below:

library(data.table)  
library(plotly)

data.table::melt(data, id.vars='Animals') %>%
plot_ly(x = ~Animals, y = ~value, type = 'bar', 
                name = ~variable, color = ~variable) %>%
      layout(yaxis = list(title = 'Count'), barmode = 'stack')

This will plot:

enter image description here

1
  • 1
    In data.table::melt(data, id.vars = "Animals") : The melt generic in data.table has been passed a data.frame and will attempt to redirect to the relevant reshape2 method; please note that reshape2 is deprecated, and this redirection is now deprecated as well. To continue using melt methods from reshape2 while both libraries are attached, e.g. melt.list, you can prepend the namespace like reshape2::melt(data). In the next version, this warning will become an error.
    – dpel
    Commented Feb 3, 2023 at 12:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.