我使用 ggploty 在 R 中制作了一个堆积条形图。它是根据测试描述进行过滤的。但是,每次我过滤某些内容时,它都会显示各个点而不是堆叠条形图。我可以用闪亮的方式制作相同的作品,但我希望它有情节,因为它更容易分享。
library(ggplot2)
library(plotly)
library(dplyr)
library(lubridate)
library(crosstalk)
library(DT)
test <- dataset %>%
group_by(Collected.Date, Test.Point.Description, Test.Result) %>%
dplyr::summarise(Count = n(), .groups = 'drop')
shared_data <- SharedData$new(test, ~Test.Point.Description)
p <- ggplot(shared_data, aes(x = Collected.Date, y = Count, fill = Test.Result)) +
geom_bar(stat = "identity", position = "stack") +
scale_fill_manual(values = c("Pass" = "blue", "Fail" = "red")) +
labs(title = "Test Results Over Time",
x = "Collected Date",
y = "Count of Test Result") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
coord_cartesian(xlim = as.Date(c("2023-07-23", "2024-01-22")))
p_interactive <- ggplotly(p)
filter_select <- filter_select(id = "filter_select", label = "Select Test Point Description", sharedData = shared_data, group = ~Test.Point.Description)
bscols(filter_select, p_interactive)
当我单击特定过滤器时,我在 R 中附加了图像。它只显示点。
这是数据集示例
结构(列表(收集。日期 = 结构(c(19577, 19577, 19577, 19577, 19577, 19577), class = "日期"), Test.Point.Description = c("屏幕", “螺旋钻”、“靴子”、“刀片”、“墙壁”、 "接缝"), Test.Result = c("通过", "通过", "通过", "通过", "通过", "失败")), row.names = c(NA, 6L), class = "data.frame")
查看您的问题后,恐怕这是从
ggplot2
到 plotly
的转换无法解释正确分组的情况之一。相反,我建议使用 plot_ly()
创建图表。
注意:我使用了一些假的随机示例数据。
library(plotly)
library(crosstalk)
library(DT)
set.seed(123)
test <- expand.grid(
Collected.Date = seq.Date(
as.Date("2023-08-08"), as.Date("2024-01-23"),
by = "week"
),
Test.Point.Description = c("screen", "auger", "Boot", "blades", "wall", "seam"),
Test.Result = c("Pass", "Pass", "Pass", "Pass", "Pass", "Fail")
)
test$Count <- sample(seq(10), size = nrow(dataset), replace = TRUE)
shared_data <- SharedData$new(test, ~Test.Point.Description)
p_interactive <- shared_data |>
plot_ly(
x = ~Collected.Date,
y = ~Count,
color = ~Test.Result
) |>
add_bars(colors = c("blue", "red")) |>
layout(
barmode = "stack",
title = "Test Results Over Time",
xaxis = list(
title = "Collected Date",
range = as.Date(c("2023-07-23", "2024-01-22"))
),
yaxis = list(title = "Count of Test Result")
)
filter_select <- filter_select(
id = "filter_select",
label = "Select Test Point Description",
sharedData = shared_data,
group = ~Test.Point.Description
)
bscols(filter_select, p_interactive)