应用过滤器会导致显示变量的所有级别
Applying filter causes all levels of a variable to show
我过滤了一个数据框,然后使用 'summarise' 获得了我想要的指标。
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 等上专门过滤。另一个问题是......这些图没有堆叠。如何解决这些问题?
输出:
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"))
我们可以在'df.2'上使用droplevels
来删除未使用的级别(假设列'state'是factor
class)
df.2 <- droplevels(df.2)
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")
如果我们希望它按升序排列,请在执行 arrange
后更改 factor
级别
df.2 %>%
arrange(V3, V2, V1) %>%
mutate(state = factor(state, levels = unique(state))) %>%
plot_ly(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")
我过滤了一个数据框,然后使用 'summarise' 获得了我想要的指标。
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 等上专门过滤。另一个问题是......这些图没有堆叠。如何解决这些问题?
输出:
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"))
我们可以在'df.2'上使用droplevels
来删除未使用的级别(假设列'state'是factor
class)
df.2 <- droplevels(df.2)
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")
如果我们希望它按升序排列,请在执行 arrange
factor
级别
df.2 %>%
arrange(V3, V2, V1) %>%
mutate(state = factor(state, levels = unique(state))) %>%
plot_ly(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")