ggplotly堆叠条形图在过滤后不调整大小

ggplotly stacked bar chart not resizing after filtering

出于某种原因,在使用 ggplotly 函数生成绘图时,过滤似乎不会调整 y 轴的大小。过滤后的部分被简单地删除,而 yaxis 保持其原始长度。请看这个例子:

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)) 
)

plot_ly 功能相同的方法有效。但是,我需要与 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')

我找不到任何有助于堆栈溢出或 google 的信息。刚刚在这里遇到一个不完整的答案: https://community.rstudio.com/t/ggplotly-bar-chart-not-resizing-after-filtering/115675/3

任何帮助将不胜感激。

应用 中的提示可以重新堆叠和类似排序,同时启用自动缩放可以提供 y 轴自适应:

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