1

I have copypasted the code example from plotly website (https://plot.ly/ggplot2/geom_bar), but the graph behave differently from the example when filtered; how can I have mine to be able to reshape like that?

code:

library(plotly)

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

p <- ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +
  geom_bar(stat = "identity")

p <- ggplotly(p)

From the web: Plotly website
My RStudio Viewer:

R Studio Viewer

edit_profile
  • 147
  • 2
  • 7

1 Answers1

1

If you compare the data produced by the example code and the published code closely, you can see two differences.

  1. The "wrong" graph has base values
  2. The order is reversed between the two graphs

In order to prevent stacked bar graphs from not collapsing if you toggle a trace, you would need to erase the base values (and for aesthetic reasons reverse the order of the traces).

library(plotly)

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

gp <- ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +
  geom_bar(stat = "identity")

p <- ggplotly(gp)

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

enter image description here

Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99
  • Hello, thank you for your answer. Would you know how to resize the yaxis too when we are filtering? https://stackoverflow.com/questions/69979194/ggplotly-stacked-bar-chart-not-resizing-after-filtering – AOE_player Nov 16 '21 at 03:08