Home > Back-end >  Create a grouped bar chart with the groups being all the unique values of a dataframe column
Create a grouped bar chart with the groups being all the unique values of a dataframe column

Time:02-02

I have the dataframe below and I want it to be displayed as a grouped bar chart as follows. In the x axis there should be the year while in the y axis count n. The complex thing is that I want the severity to be displayed as a grouped bar chart with a different color for every unique value of severity (2,3,4). something like:

enter image description here

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

CodePudding user response:

Just replace name = 'severity' with color = ~severity and you'll get this:

enter image description here

CodePudding user response:

We may do this by creating a ggplot object and then wrap with 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)
  •  Tags:  
  • Related