我有一个直方图,我希望工具提示显示该箱中观测值的百分比。
这是一个简单的(可重现的)直方图:
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/