AOE_player
AOE_player

Reputation: 556

ggplotly stacked bar chart not resizing after filtering

For some reason when producing a plotly graph with the ggplotly function, the filtering does not seem to resize the y-axis. The filtered portion are simply removed, while yaxis stays at it's original length. Please see this example:

library(plotly)
library(ggplot2)
library(dplyr)

lab <- paste("Vertical Label", c(1, 2, 3, 4, 5))

ds <- data.frame(x = sample(lab, size = 1000, replace = T),
                 y = sample(LETTERS[1:5], size = 1000, replace = T)) %>%
      group_by(x,y) %>% summarise(count= n())

ggplotly(
ggplot(ds, aes(x = x,y=count, fill = y)) +
  geom_col() +
  theme(axis.text.x = element_text(angle = 90)) 
)

enter image description here

Same approach with plot_ly function works. However, I needed similar results with ggploty

plot_ly(ds, x = ~x, y = ~count, type = 'bar', color = ~y
        ) %>% layout(title = "Vertical Axis Lables",
                      xaxis = list(title = ""),
                      yaxis = list(title = ""), barmode = 'stack')

enter image description here

I couldn't find anything helpful in stack overflow or google. Just came across an incomplete answer here: https://community.rstudio.com/t/ggplotly-bar-chart-not-resizing-after-filtering/115675/3

Any help will be greatly appreciated.

Upvotes: 3

Views: 584

Answers (2)

Melanie Lou
Melanie Lou

Reputation: 99

It is only necessary to reset the base of the plotly variable for each of the x-axis elements that will be plotted.

for (i in 1:length(p$x$data)) {
  p$x$data[[i]]$base <- c()
}

In the above example, if you reset the order, (1) D does not resize and (2) purple overlays A (A is never seen unless purple is filtered).

Upvotes: 1

user1533380
user1533380

Reputation:

Applying a tip from R Plotly Legend Filtering enables re-stacking and similar ordering, while enabling auto-scaling provides y-axis adaptation:

library(plotly)
library(ggplot2)
library(dplyr)

lab <- paste("Vertical Label", c(1, 2, 3, 4, 5))

ds <- data.frame(x = sample(lab, size = 1000, replace = T),
             y = sample(LETTERS[1:5], size = 1000, replace = T)) %>%
             group_by(x,y) %>% summarise(count= n())

p <- ggplotly(
  ggplot(ds, aes(x = x,y=count, fill = y)) +
    geom_col() +
    theme(axis.text.x = element_text(angle = 90)) 
)
for (i in 1:length(p$x$data)) {
  p$x$data[[i]]$base <- c()
  tmp <- p$x$data[[i]]
  p$x$data[[i]] <- p$x$data[[length(p$x$data) - i + 1]]
  p$x$data[[length(p$x$data) - i + 1]] <- tmp
}
p

Filtered plot

Upvotes: 2

Related Questions