How to generate pltoly grouped bar chart with pivot_longer (or gather) data

I want to generate a grouped bar chart with plotly.

Here is the data:

df <- data.frame(structure(list(Animals = structure(c(1L, 1L, 1L, 3L, 3L, 3L, 
2L, 2L, 2L), .Label = c("giraffes", "monkeys", "orangutans"), class = "factor"), 
    name = c("SF_Zoo", "LA_Zoo", "DC_Zoo", "SF_Zoo", "LA_Zoo", 
    "DC_Zoo", "SF_Zoo", "LA_Zoo", "DC_Zoo"), value = c(20, 12, 
    6, 14, 18, 14, 23, 29, 25)), .Names = c("Animals", "name", 
"value"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-9L)))

The expected render is

I can generate the plot with pivot_wider data and with #ggplot2 but need to render it with plotly and in "pivot_longer" format for large data dashboard integration.

Hi @abiyug. You may try the following code and text color to visualise it.

library(tidyverse)

df <- data.frame(structure(list(Animals = structure(c(1L, 1L, 1L, 3L, 3L, 3L, 
                                                      2L, 2L, 2L), .Label = c("giraffes", "monkeys", "orangutans"), class = "factor"), 
                                name = c("SF_Zoo", "LA_Zoo", "DC_Zoo", "SF_Zoo", "LA_Zoo", 
                                         "DC_Zoo", "SF_Zoo", "LA_Zoo", "DC_Zoo"), value = c(20, 12, 
                                                                                            6, 14, 18, 14, 23, 29, 25)), .Names = c("Animals", "name", 
                                                                                                                                    "value"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
                                                                                                                                                                                                      -9L)))
df %>%
  mutate(name = factor(name, levels = c("SF_Zoo", "LA_Zoo", "DC_Zoo"))) %>%
  plotly::plot_ly(x = ~ Animals, y = ~ value, color = ~name, type = "bar",
                  text = df$value, textposition = "auto", textfont = list(color = 'rgb(0,0,0)'))

1 Like

Thanks @raytong that did it!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.