应用过滤器会显示变量的所有级别

问题描述 投票:0回答:1

我过滤了一个数据框,然后使用“汇总”来获取所需的指标。

df.2 <- df.1 %>% filter(state %in% c("NY", "NJ", "MI", "LA", "WA")) %>% group_by(state) %>% 
  summarise(V1 = max(v1), V2 = max(v2), V3 = max(v3))

然后当我这样做时...

plot_ly(df.2, x = ~state, y = ~V1, type = "bar", name = "Name1") %>%
  add_trace(y = ~V2, name = "Name2") %>% add_trace(y = ~V3, name = "Name3") %>%
  layout(yaxis = list(title = "Count", barmode = "stack"))

所有状态都显示在x轴上,尽管专门过滤了NY,NJ等。另一个问题是...这些图没有堆叠。如何解决这些问题?

Dput:

structure(list(state = structure(1:5, .Label = c("LA", "MI", 
"NJ", "NY", "WA"), class = "factor"), V1 = c(582, 845, 1232, 
5489, 372), V2 = c(16284, 18970, 44416, 138863, 8384), 
    V3 = c(58371, 31362, 50558, 201195, 83391)), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"))
r plotly bar-chart stacked
1个回答
0
投票

我们可以在'df.2'上使用droplevels删除未使用的级别(假设列'state'是factor类)

df.2 <- droplevels(df.2)
© www.soinside.com 2019 - 2024. All rights reserved.