使用工具提示或悬停显示总计

时间:2021-03-09 07:53:52

标签: r ggplot2 plotly ggplotly

借助此代码,我可以获得每个条形的总数,但如何使用悬停或工具提示功能显示此总数

#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

1 个答案:

答案 0 :(得分:1)

您可以在数据中为每个 sum 使用 amountclass 创建一个新列:

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