【发布时间】:2018-12-18 01:31:11
【问题描述】:
如何在 plotly 中创建具有下拉菜单(或其他内容)的分组条形图,以便查看者可以选择分组变量?
工作示例:
library(dplyr)
library(plotly)
library(reshape2)
iris$Sepal.L <- iris$Sepal.Length %>%
cut(breaks = c(4,5,7,8),
labels = c("Length.a","Length.b","Length.c"))
iris$Sepal.W <- iris$Sepal.Width %>%
cut(breaks = c(1,3,5),
labels = c("Width.a","Width.b"))
# Get percentages
data1 <- table(iris$Species, iris$Sepal.L) %>%
prop.table(margin = 1)
data2 <- table(iris$Species, iris$Sepal.W) %>%
prop.table(margin = 1)
# Convert to df
data1 <- data.frame(Var1=row.names(data1), cbind(data1))
row.names(data1) <- NULL
data2 <- data.frame(Var1=row.names(data2), cbind(data2))
row.names(data2) <- NULL
plot_ly(
data = data1,
name = "Length.a",
x = ~Var1, y = ~Length.a,
type = "bar") %>%
add_trace(y=~Length.b, name = "Length.b") %>%
add_trace(y=~Length.c, name = "Length.c")
plot_ly(
data = data2,
name = "Width.a",
x = ~Var1, y = ~Width.a,
type = "bar") %>%
add_trace(y=~Width.b, name = "Width.b")
例如,如果我想在查看带有 table(iris$Species, iris$Sepal.Length) 的绘图和使用 table(iris$Species, iris$Sepal.Width) 的绘图之间进行选择
奖金:
如果这很容易;能够以交互方式选择 x 变量也很酷,但不是必需的。
【问题讨论】:
-
顺便说一句,我想在没有 Shiny 的情况下完成这个。