0

With the help of this code i can get total for each bar but how to show this total using hover or tooltip function

#Data
    hp=read.csv(textConnection(
      "class,year,amount
    a,99,100
    a,100,200
    a,101,150
    b,100,50
    b,101,100
    c,102,70
    c,102,80
    c,103,90
    c,104,50
    d,102,90"))
    hp$year=as.factor(hp$year)
   

d = ggplot(hp, aes(reorder(class, -amount, sum), amount, fill = year)) +
  geom_col() 
  #geom_text(aes(label = stat(y), group = class),stat = 'summary', fun = sum,vjust = -1)

ggplotly(d)sample chart

Fariya
  • 234
  • 1
  • 11
  • You tagged your question with `ggplotly` but don't seem to be using the package at all? Have you tried anything yet? Base ggplot2 doesn't allow for hovering interactions but using `ggplotly` should. This existing question might help: https://stackoverflow.com/questions/34605919/formatting-mouse-over-labels-in-plotly-when-using-ggplotly – MrFlick Mar 09 '21 at 07:57
  • i tried but its not showing the total of the bar @MrFlick – Fariya Mar 09 '21 at 08:02

1 Answers1

1

You can create a new column in the data with sum of amount for each class :

library(dplyr)
library(ggplot2)
library(plotly)

plot1 <- hp %>%
  group_by(class, year) %>%
  summarise(amount = sum(amount)) %>%
  mutate(total_sum = sum(amount)) %>%
  ggplot(aes(class, amount, fill = year, text = total_sum)) +
  geom_col() +
  geom_text(aes(label = amount), vjust = -1, 
            position = position_stack(vjust = .5))


ggplotly(plot1, tooltip = 'text')

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213