1
votes

I have a data frame which I want to display in a grouped and stacked bar chart with ggplotly.

library(ggplotly)
library(dplyr)
library(tidyr)


year = rep(c(2019,2019,2020,2020), 2)
month = rep(c("June","July"), 4)
gender = c("M","M","M","M","F","F","F","F")
male = c(11,13,15,17)
female = c(12,14,16,18)
count = c(11,13,15,17,12,14,16,18)

df <- data.frame(year, month, gender, count = as.numeric(count))

p <- df %>%
  mutate(count=as.numeric(count),
         month=factor(month, levels=c("June","July")),
         Month=paste(year,month,sep="-")) %>%
  ggplot(aes(month, count, fill=gender)) +
  geom_bar(stat="identity", position=position_stack()) +
  theme_minimal() + xlab("") + 
  facet_grid(~year, switch='x') + 
  theme(axis.text.x = element_text(margin = margin(t = -1, unit = "cm")))

ggplotly(p)

enter image description here

This works fine but when I deselect "M" in the legend the "F"-bars remain floating in their original position and do not move down to the x-axis. What am I doing wrong?

enter image description here

1
Possible duplicate. Solved by using plot_ly. See: stackoverflow.com/questions/45326425/…Pierre
Similar description here: github.com/ropensci/plotly/issues/1366TTS
It is not a duplicate since my chart is grouped and stacked.volfi
isn't the package plotly not ggplotly?Daniel Jachetta

1 Answers

1
votes

Try to apply dcast in your data and use plotly.

dt <- data.table(df) ## converts it to data.table
dt <- dcast.data.table(dt, year + month ~ gender, value.var = 'count') # dcast

fig <- plot_ly(dt, x = ~month, y = ~F, type = 'bar', name = 'F')
fig <- fig %>% add_trace(y = ~M, name = 'M')
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'stack')

fig