Plotly R: create dividers in bar plot like Tableau

Viewed 23

I have this dataframe:

df = data.frame(
  Period = c("FY2015", "FY2015", "FY2015", "FY2015", "FY2015", "FY2015", "FY2016", "FY2016", 
              "FY2016", "FY2016", "FY2016", "FY2016"),
  Region = c("Africa", "Asia", "Australia", "Europe", "North America", "South America", 
             "Africa", "Asia", "Australia", "Europe", "North America", "South America"),
  Revenue = c(1.0e+07, 2.0e+07, 7.0e+07, 1.2e+08, 1.5e+08, 6.0e+07, 8.0e+06, 1.6e+07, 5.6e+07, 
              9.6e+07, 1.2e+08, 4.8e+07))

I would like to have a plotly bar plot in divided by Region, just like I did here in Tableau.

Any tips here?

1 Answers

I don't know a totally automatic way, but we can fake it by making facets, removing the padding between them, and adding vertical lines at the borders.

In this case, with two discrete categories ("FY2015" and "FY2016"), ggplot treats them under the hood as values of 1 and 2. The default bar width and padding means that the edges of these panels are at 0.4 on the right and 2.6 on the right.

library(ggplot2)
library(plotly)

my_plot <- ggplot(df, aes(Period, Revenue)) +
  geom_col() +
  geom_vline(xintercept = c(0.4, 2.6), size = 0.2, color = "gray70") +
  facet_wrap(~Region, nrow = 1) +
  theme_minimal() +
  theme(panel.grid.major.x = element_blank(),
        panel.spacing = unit(0, "cm"))

ggplotly(my_plot)

enter image description here

Related