cowboy
cowboy

Reputation: 661

How do I split grouped bar chart in R by variable

I am trying to split the attached grouped bar chart by the variable spec. Two thoughts on best way to do this are by adding facet_grid() or if a filter can be applied to the static output? Can either be done? Any advice appreciated.

a sample is below:

period <- c('201901', '201901', '201904', '201905')
spec <- c('alpha', 'bravo','bravo', 'charlie')
c <-  c(5,6,3,8)
e <- c(1,2,4,5)


df <- data.frame(period, spec, c,e)

library(tidyverse)
library(plotly)

plot_ly(df, x =~period, y = ~c, type = 'bar', name = "C 1", marker = list(color = 'lightsteelblue3')) 
%>%
  add_trace(y = ~e, name = "E 1", marker = list(color = 'Gray')) %>%
  layout(xaxis = list(title="", tickangle = -45),
         yaxis = list(title=""),
         margin= list(b=100), 
         barmode = 'group'
  )

Upvotes: 0

Views: 2207

Answers (2)

Maurits Evers
Maurits Evers

Reputation: 50668

It's probably easier to use facets here, but a more "interactive" option would be to use a filter transforms which gives you a drop-down menu in the top left corner of your plot.

spec.val <- unique(df$spec)
plot_ly(
    df %>% pivot_longer(-c(period, spec)),
    x = ~period, y = ~value, color = ~name,
    type = "bar",
    transforms = list(
        list(
            type = "filter",
            target = ~spec,
            operation = "=",
            value = spec.val[1]))) %>%
    layout(
        updatemenus = list(
            list(
                type = "drowdown",
                active = 0,
                buttons = map(spec.val, ~list(
                    method = "restyle",
                    args = list("transforms[0].value", .x),
                label = .x)))))

enter image description here

Upvotes: 1

tjebo
tjebo

Reputation: 23737

I am not sure if you are plotting what you actually want to achieve? My suggestion is to create your plot using standard ggplot and then use ggplotly.

For this, you also need to reshape your data and make it a bit longer.

library(tidyverse)
library(plotly)

period <- c('201901', '201901', '201904', '201905')
spec <- c('alpha', 'bravo','bravo', 'charlie')
c <-  c(5,6,3,8)
e <- c(1,2,4,5)


df <- data.frame(period, spec, c,e) %>% 
        pivot_longer(cols = c(c,e), names_to = 'var', values_to = 'val')


p <- ggplot(df, aes(period, val, fill = var)) +
  geom_col(position = position_dodge()) +
  facet_grid(~spec)

ggplotly(p)

enter image description here

Upvotes: 1

Related Questions