要按图例选择子集数据并使用ggplotly的geom_bar函数进行可视化,可以按照以下步骤进行:
library(ggplot2)
library(plotly)
df <- data.frame(
x = c("A", "B", "C", "A", "B", "C"),
y = c(10, 15, 12, 8, 6, 9),
group = c("Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2")
)
p <- ggplot(data = df, aes(x = x, y = y, fill = group)) + geom_bar(stat = "identity")
p <- ggplotly(p)
p <- p %>% event_register("plotly_legendclick")
subset_data <- reactive({
legend_click <- event_data("plotly_legendclick")
if(is.null(legend_click)){
return(df)
} else {
selected_group <- legend_click[["curveNumber"]] + 1
subset_df <- df[df$group == unique(df$group)[selected_group], ]
return(subset_df)
}
})
p <- p %>% event_reactive("plotly_legendclick", function() {
subset_df <- subset_data()
new_trace <- subset_df %>% plot_ly(x = ~x, y = ~y, type = "bar", color = ~group)
p <- add_trace(p, new_trace)
})
完整的代码示例如下:
library(ggplot2)
library(plotly)
df <- data.frame(
x = c("A", "B", "C", "A", "B", "C"),
y = c(10, 15, 12, 8, 6, 9),
group = c("Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2")
)
p <- ggplot(data = df, aes(x = x, y = y, fill = group)) + geom_bar(stat = "identity")
p <- ggplotly(p)
p <- p %>% event_register("plotly_legendclick")
subset_data <- reactive({
legend_click <- event_data("plotly_legendclick")
if(is.null(legend_click)){
return(df)
} else {
selected_group <- legend_click[["curveNumber"]] + 1
subset_df <- df[df$group == unique(df$group)[selected_group], ]
return(subset_df)
}
})
p <- p %>% event_reactive("plotly_legendclick", function() {
subset_df <- subset_data()
new_trace <- subset_df %>% plot_ly(x = ~x, y = ~y, type = "bar", color = ~group)
p <- add_trace(p, new_trace)
})
p
这将创建一个交互式柱形图,可以通过单击图例中的组来选择子集数据。
上一篇:antubuntu安装配置
下一篇:按图像捕获日期过滤街景视图