In the plot below I want the bars not to be displayed like they are into pieces. The Total Value
to be displayed as whole and not for every piece and the Year to be displayed not as(factor) Year
inside hover box.
counts<-structure(list(Year = c(2023, 2023, 2023, 2023, 2023, 2024, 2024,
2024, 2024, 2024), `Attribute Name` = c("2020", "2021", "2022",
"2023", "2024", "2020", "2021", "2022", "2023", "2024"), `Sub Header 1` = c("Year of first Trodelvy LOT",
"Year of first Trodelvy LOT", "Year of first Trodelvy LOT", "Year of first Trodelvy LOT",
"Year of first Trodelvy LOT", "Year of first EV LOT", "Year of first EV LOT",
"Year of first EV LOT", "Year of first EV LOT", "Year of first Trodelvy LOT"
), Total_Value = c(1, 11, 17, 9, 0, 3, 33, 51, 27, 1)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L), groups = structure(list(
Year = c(2023, 2023, 2023, 2023, 2023, 2024, 2024, 2024,
2024, 2024), `Attribute Name` = c("2020", "2021", "2022",
"2023", "2024", "2020", "2021", "2022", "2023", "2024"),
.rows = structure(list(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -10L), .drop = TRUE))
library(plotly)
plot <- ggplot(counts, aes(x = as.factor(Year), y = Total_Value, fill = `Sub Header 1`)) +
geom_bar(stat = "identity",width=0.1) +
labs(title = "ADC Treatment Start by Calendar Year",
x = "Year of ADC start",
y = "Patient Counts") +
theme_minimal()
# Customize colors
plot <- plot + scale_fill_manual(values = c("maroon", "darkblue"))
# Place legend under the plot
plot <- plot + theme(legend.position = "bottom")
# Display the plot
ggplotly(plot)
Udate based on OP's comment
A way to approach this is to first summarise()
your data as a new dataframe.
To customise your hover box text, use text =
inside your aes()
, and then call it at ggplotly()
.
library(dplyr)
library(plotly)
# Summarise counts data
counts1 <- ungroup(counts) |>
summarise(Total_Value = sum(Total_Value), .by = c(Year, `Sub Header 1`))
plot <- ggplot(counts1,
aes(x = as.factor(Year), y = Total_Value, fill = `Sub Header 1`,
text = paste("Year:", Year,
"\nTotal Value:", Total_Value,
"\nType:", `Sub Header 1`))) +
geom_bar(stat = "identity", width = 0.1) +
labs(title = "ADC Treatment Start by Calendar Year",
x = "Year of ADC start",
y = "Patient Counts") +
theme_minimal()
# Customize colors
plot <- plot + scale_fill_manual(values = c("maroon", "darkblue"))
# Place legend under the plot
plot <- plot + theme(legend.position = "bottom")
# Display the plot
ggplotly(plot, tooltip = "text")