带浮动条形的堆积条形图

问题描述

我有一个数据框,希望通过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","F","F")
male = c(11,13,15,17)
female = c(12,14,16,18)
count = c(11,17,12,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,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

这很好用,但是当我在图例中取消选择“ M”时,“ F”-条保持浮动在其原始位置,并且不向下移动到x轴。我在做什么错了?

enter image description here

解决方法

尝试在数据中应用dcast并进行绘图使用。

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...