创建一个分组条形图,其中组是数据框列的所有唯一值

Create a grouped bar chart with the groups being all the unique values of a dataframe column

我有下面的数据框,我希望它显示为如下所示的分组条形图。在 x axis 中应该有 year 而在 y axis 中计数 n。复杂的是,我希望 severity 显示为分组条形图,对于 severity (2,3,4) 的每个唯一值具有不同的颜色。 类似于:

library(plotly)
df2<-structure(list(year = c("2017", "2018", "2018", "2019", "2019", 
"2019", "2019", "2019", "2020", "2020", "2020", "2020", "2020"
), severity = c("2", "3", "4", "2", "2", "3", "3", "3", "2", 
"3", "3", "3", "4"), accident.description = c("right lane blocked", 
"two lanes blocked", "road closed", "one lane blocked", "right lane blocked", 
"one lane blocked", "right lane blocked", "two lanes blocked", 
"right lane blocked", "right and center lane blocked", "right lane blocked", 
"two lanes blocked", "two lanes blocked"), n = c(3L, 1L, 1L, 
1L, 2L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 2L)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -13L), groups = structure(list(
    year = c("2017", "2018", "2018", "2019", "2019", "2020", 
    "2020", "2020"), severity = c("2", "3", "4", "2", "3", "2", 
    "3", "4"), .rows = structure(list(1L, 2L, 3L, 4:5, 6:8, 9L, 
        10:12, 13L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -8L), .drop = TRUE))

fig <- plot_ly(df2, x = ~year, y = ~n, type = 'bar', name = 'severity',
               hovertext = paste(
                 "<br>Year :",
                 df2$year,
                 "<br>Severity :",
                 df2$severity,
                 "<br>Accident Description :",
                 df2$accident.description,
                 paste("<br> Count:"),
                 df2$n
               ),
               hoverinfo = "text")
fig

我们可以通过创建一个 ggplot 对象然后用 ggplotly

包装来做到这一点
library(plotly)
library(ggplot2)
library(dplyr)

p <- df2 %>%
   ungroup %>%
   ggplot(aes(x = year, y = n, fill = severity)) +
   geom_col(position= "dodge") +
   theme_bw()

ggplotly(p)

只需将 name = 'severity' 替换为 color = ~severity 即可得到: