Fariya
Fariya

Reputation: 284

showing total using tooltip or hovering

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

Upvotes: 0

Views: 187

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389055

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

Upvotes: 1

Related Questions