r - 在 ggplot 直方图上显示带有观察总数百分比的工具提示?

标签 r ggplot2 histogram ggplotly

我有一个直方图,我希望工具提示显示该箱中观测值的百分比。

这是一个简单的(可重现的)直方图:

library(tidyverse)
library(ggplot2)
library(plotly)
 
hist <- iris %>%
  ggplot(aes(x = Sepal.Length)) +
  geom_histogram(bins = 20)
 
hist %>%
  ggplotly(
    # This gives hoverover the count and the variable, but I'd like it
    # to also have the percent of total observations contained in that bin
    tooltip=c("count", "Sepal.Length")
  )

 

除了“count”和“Sepal.Length”之外,我还想在工具提示中显示观察总数的百分比。

例如,最左边的 bin(包含 4 个观测值)的值为 2.7% (4/150)

最佳答案

我会尝试在ggplot中使用text参数,并将其设置为计数除以所有计数的总和。使用sprintf您可以获得所需的格式。在您的工具提示中引用文本

library(tidyverse)
library(ggplot2)
library(plotly)

hist <- iris %>%
  ggplot(aes(x = Sepal.Length, 
             text = sprintf("Percent: %0.1f", ..count../sum(..count..) * 100))) +
  geom_histogram(bins = 20)

hist %>%
  ggplotly(
    tooltip=c("count", "text", "Sepal.Length")
  )

关于r - 在 ggplot 直方图上显示带有观察总数百分比的工具提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70827413/

相关文章:

python - 为分组列创建直方图

pandas - 在 Pandas 直方图中设置 y 轴限制

python - 在 Altair 中控制箱宽度

R:如何显示一串单词的前n个字符

r - viterbi RHmm 错误保护堆栈溢出

r - 如何在ggplot2中将热图和散点图一个放在另一个之上

R ggplot 添加新的 roc 曲线

r - 如何将一列(逗号拆分)转换为 R 中的多列?

r - 合并 R 中不同行的两个数据帧

r - sjPlot - 将绘图线颜色更改为黑色/白色