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