我正在使用 stat_summary 從資料框中生成列圖。我想使用 ggiraph 中的 geom_col_interactive 通過工具提示向用戶報告這些值。
我可以使用 ggplot_build 從 ggplot 獲取值并構建如下的工具提示。但是,我無法弄清楚如何將 ggiraph 與使用 stat_summary 生成的繪圖一起使用以互動方式呈現工具提示。我當然可以使用 summary_values tibble 并使用 geom_col_interactive 生成??不同的 ggplot,但這會破壞使用 stat_summary 的目的(這很適合分面)。有沒有辦法做到這一點?還是我必須使用 Rmisc 中的 summarySE 來生成要使用 geom_col_interactive 繪制的小標題?
library(tidyverse)
mpg_histogram <- ggplot(mpg, aes(x=as.factor(cyl), fill = as.factor(cyl)))
stat_summary(aes(y = hwy), fun = "mean", geom = "bar")
stat_summary(aes(y = hwy), fun.data = mean_se,
geom = "errorbar", width = 0.2, size = 0.2)

summary_values <- ggplot_build(mpg_histogram)$data[[2]]
summary_values <- summary_values %>%
mutate(mean = round(y,1), sem = round(ymax-y,1)) %>%
mutate(tooltip = paste("Mean mpg:",mean," /-",sem)) %>%
select(c(mean,sem,tooltip))
uj5u.com熱心網友回復:
實作所需結果的一種方法stat_summary是將 傳遞ggiraph:::GeomInteractiveCol給geom引數。但是,請注意,GeomInteractiveCol它不是由匯出的ggiraph,因此需要使用:::. 此外,要在工具提示中同時顯示均值和標準誤差,需要切換到fun.data="mean_se". 為方便起見,我使用一個簡單的自定義函式來創建工具提示:
library(ggplot2)
library(ggiraph)
tooltip <- function(y, ymax, accuracy = .01) {
mean <- scales::number(y, accuracy = accuracy)
sem <- scales::number(ymax - y, accuracy = accuracy)
paste("Mean mpg:", mean, " /-", sem)
}
gg_point <- ggplot(mpg, aes(x = as.factor(cyl), fill = as.factor(cyl)))
stat_summary(aes(y = hwy, tooltip = after_stat(tooltip(y, ymax))),
fun.data = "mean_se", geom = ggiraph:::GeomInteractiveCol
)
stat_summary(aes(y = hwy),
fun.data = mean_se,
geom = "errorbar", width = 0.2, size = 0.2
)
girafe(ggobj = gg_point)

uj5u.com熱心網友回復:
以下是不使用的解決方法GeomInteractiveCol()和替代/快捷方式after_stat():
library(ggplot2)
library(ggiraph)
tooltip <- function(y, ymax, accuracy = .01) {
mean <- scales::number(y, accuracy = accuracy)
sem <- scales::number(ymax - y, accuracy = accuracy)
paste("Mean mpg:", mean, " /-", sem)
}
gg_point <- ggplot(mpg)
aes(x = as.factor(cyl), fill = as.factor(cyl), y = hwy,
tooltip = tooltip(..y.., ..ymax..)
)
geom_bar_interactive(fun.data = "mean_se", stat = "summary")
geom_errorbar_interactive(fun.data = "mean_se", stat = "summary",
width = 0.2, size = 0.2
)
girafe(ggobj = gg_point)
我個人更喜歡使用geom_語法而不是語法stat_,因為它與 ggplot 代碼的其余部分更一致。
這是一種在一個命令中執行此操作的方法glue(),但由于未知原因,它仍然需要after_stat():
{ggplot(mpg)
aes(x = as.factor(cyl), fill = as.factor(cyl), y = hwy,
tooltip = glue("Mean mpg: {round(y, 2)} /- {round(ymax, 2)}") %>% after_stat()
)
geom_bar_interactive(fun.data = "mean_se", stat = "summary")
geom_errorbar_interactive(fun.data = "mean_se",
stat = "summary", width = 0.2, size = 0.2)
} %>%
girafe(ggobj = .)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462767.html
