I have made a stacked bar graph in R using ggploty . It's filtered based on a test description. However, every time I filter something, it is showing individual points not the stacked bar graph. I can make the same work in shiny but I want it ploty because it's easier to share.
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)
I attached image in R when I click on a specific filter. it just shows the dots.
here is the data set example
structure(list(Collected.Date = structure(c(19577, 19577, 19577, 19577, 19577, 19577), class = "Date"), Test.Point.Description = c("screen", "auger", "Boot", "blades", "wall", "seam"), Test.Result = c("Pass", "Pass", "Pass", "Pass", "Pass", "Fail")), row.names = c(NA, 6L), class = "data.frame")
After a look at your issue I'm afraid that this is one of the cases where the conversion from ggplot2
to plotly
fails to account for the correct grouping. Instead I would suggest to create your chart using plot_ly()
.
Note: I use some fake random example data.
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)