[英]Positioning legend title on top of horizontal legend causes loss of interactivity in ggiraph
當我使用 guides() 規范自定義圖例外觀時,我發現圖例中圖例的交互性丟失了。
以下代碼修改自 ggiraph 文檔中的示例。
library(ggplot2)
library(ggiraph)
dat <- data.frame(
name = c( "Guy", "Ginette", "David", "Cedric", "Frederic" ),
gender = c( "Male", "Female", "Male", "Male", "Male" ),
height = c(169, 160, 171, 172, 171 ) )
p <- ggplot(dat, aes( x = name, y = height, fill = gender,
data_id = name ) ) +
geom_bar_interactive(stat = "identity")
p1 <- p + scale_fill_manual_interactive(
values = c(Male = "#0072B2", Female = "#009E73"),
data_id = function(breaks) { as.character(breaks)},
tooltip = function(breaks) { as.character(breaks)},
onclick = function(breaks) { paste0("alert(\"", as.character(breaks), "\")") },
labels = function(breaks) {
lapply(breaks, function(br) {
label_interactive(
as.character(br),
data_id = as.character(br),
onclick = paste0("alert(\"", as.character(br), "\")"),
tooltip = as.character(br)
)
})
}
) +
guides(fill=guide_legend(title.position = "top")) +
theme(legend.position="top")
girafe_options(girafe(ggobj = p1),
opts_hover_key(girafe_css("stroke:red", text="stroke:none;fill:red")))
如果沒有guides(fill=guide_legend(title.position = "top"))
行,圖例將保留其交互性。
任何幫助都非常感謝!
不是通過guides()
更改標題位置,您可以通過scale_fill_manual_interactive
的guide
參數在不丟失交互性的情況下實現您想要的結果:
library(ggplot2)
library(ggiraph)
dat <- data.frame(
name = c("Guy", "Ginette", "David", "Cedric", "Frederic"),
gender = c("Male", "Female", "Male", "Male", "Male"),
height = c(169, 160, 171, 172, 171)
)
p <- ggplot(dat, aes(
x = name, y = height, fill = gender,
data_id = name
)) +
geom_bar_interactive(stat = "identity")
p1 <- p + scale_fill_manual_interactive(
values = c(Male = "#0072B2", Female = "#009E73"),
data_id = function(breaks) {
as.character(breaks)
},
tooltip = function(breaks) {
as.character(breaks)
},
onclick = function(breaks) {
paste0("alert(\"", as.character(breaks), "\")")
},
labels = function(breaks) {
lapply(breaks, function(br) {
label_interactive(
as.character(br),
data_id = as.character(br),
onclick = paste0("alert(\"", as.character(br), "\")"),
tooltip = as.character(br)
)
})
},
guide = guide_legend(title.position = "top")
) +
theme(legend.position = "top")
girafe_options(
girafe(ggobj = p1),
opts_hover_key(girafe_css("stroke:red", text = "stroke:none;fill:red"))
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.