Search code examples
rggplot2ggplotly

How to Change the Tooltip in ggplotly to show SUM of a Column in a Bar Chart


I have this bar chart rendered using ggplot and ggplotly()

It renders just the way I want, in that it displays the SUM of total crashes by Mode Type and Year.

But, I am struggling with getting the (hover) tooltip to display the SUM of the Total Crashes. Right now, it just shows "1".

What do I need to do to my code to configure the tool tip to show the total crashes as shown in the chart, and not a value of 1? Here is my code, and the bar chart it produces:

crashplot <- ggplot(totcrashes_by_year, aes(totcrashes_by_year$`Crash Year`, totcrashes_by_year$`Total Crashes`))
crashplot +geom_bar(stat = "identity", 
                        aes(fill=totcrashes_by_year$`Mode Type`), position = "stack") + xlab("Crash Year") + ylab("Total Crashes") + ggtitle("Total Crashes by Year and Mode Type") + labs(fill = "Mode Type")

ggplotly tool tip - How do I show the sum of the crashes for each year?

EDIT: Reproducible Code Example Here is code for replicating this issue.

crashsample <- data.frame(year = sample(2007:2018, 40, replace = T),
             crashes = 1, 
             type = sample(c('Vehicle', 'Pedestrian','Bike','Motorcycle'), 5, replace = TRUE))

Create ggplot

crashplot <- ggplot(crashsample, aes(x =  year, y = crashes, fill = type)) +
  geom_bar(stat = "identity") + 
  labs(x = 'Crash Year', 
       y = 'Total Crashes', 
       title = "Total Crashes by Year and Mode Type", 
       fill = "Mode Type")
#call to ggplotly to render as a dynamic plotly chart
ggplotly(crashplot)

Solution

  • This code returns valid labels for me

    # Simulate Data
    df <- data.frame(year = sample(2005:2015, 20, replace = T),
                     crashes = sample(30:100, 20), 
                     type = sample(c('Vehicle', 'Pedestrian'), 20, replace = TRUE))
    # Required packages
    require(plotly); require(tidyverse)
    # ggplot2 plot definition
    crashplot <- df %>%
      group_by(year, type) %>%
      summarise(summed_crashes = sum(crashes)) %>%
      ggplot(., aes(x = year, y = summed_crashes, fill = type)) +
      geom_bar(stat = 'identity') + 
      labs(x = 'Crash Year',
           y = 'Total Crashes',
           title = 'Total Crashes by Year and Mode Type',
           fill = "Mode Type")
    # Show plot with plotly
    ggplotly(crashplot)
    

    Resulting plotly plot

    If it does not work, it would be good to see reproducible data example for this problem.