在 R 的条形图中绘制自定义悬停文本

Plotly custom hover text in barplot from R

我想要一个用 ggplot2 制作的堆栈条形图,我正在应用 ggplotly() 命令将其转换为交互式绘图。

现在的问题是,我希望根据 ITEM 在悬停每个值时显示绘图。

这就是我的意思...

该图显示每个项目的累积值,例如,绿色条图例显示红色条(因为它出现在前面)加上绿色条值本身。

我希望每个图例根据 ITEM 显示自己的值。

这是DF:

> plotlydata
  Fecha Item  Suma
1 05/16  BAB 20540
2 05/16  BZO  1000
3 05/16  CLZ  1400
4 05/16  CMS 15000
5 07/16  BAB   400

所以绿色条不会显示 21540(之前的 20540 和自己的 1000 的总和)会显示它自己的值 1000。

如果你明白我的意思。有什么办法吗?

不希望 plotly 显示累计值。

您可以通过添加文本美学并将其包含在工具提示参数中来添加该信息:

# they use the paste() trick on https://plot.ly/ggplot2/interactive-tooltip/
ggplot(d, aes(y = Suma, x = Fecha, fill = Item, text = paste("Suma:", Suma))) + 
  geom_bar(stat = "identity")

ggplotly(tooltip = c("text", "x", "fill"))

示例数据:

d <- read.table(text ="   Fecha Item  Suma
1 05/16  BAB 20540
2 05/16  BZO  1000
3 05/16  CLZ  1400
4 05/16  CMS 15000
5 07/16  BAB   400", header = TRUE)