我有一個函式可以生成一個繪圖,用戶可以在其中指定是否根據分組變數為線段著色:
## libraries
library(tidyverse)
library(plotly)
## data
df <- data.frame(grp = c("a", "b"),
val_start = c(1, 2),
val_end = c(5, 6))
df_long <- df %>%
pivot_longer(cols = -grp, names_to = "metric", values_to = "val")
## function
plot_func <- function(plot_color) {
## create main plot object
plot_obj <- df %>%
plot_ly()
## generate colored/non-colored segments depending on user selection
if(plot_color == T) {
plot_obj <- plot_obj %>%
add_segments(x = ~val_start,
xend = ~val_end,
y = ~grp,
yend = ~grp,
color = ~grp,
colors = c("a" = "red", "b" = "blue"))
} else {
plot_obj <- plot_obj %>%
add_segments(x = ~val_start,
xend = ~val_end,
y = ~grp,
yend = ~grp)
}
## generate primary colors
plot_obj %>%
add_markers(inherit = F,
data = df_long,
x = ~val,
y = ~grp,
showlegend = F,
marker = list(color = "green")) %>%
## generate goal marker
add_markers(name = "goal",
x = 4,
y = ~grp,
marker = list(color = "black"))
}
如下圖所示,當用戶選擇給繪圖著色時,該函式可以正常作業:
## render plot
plot_func(plot_color = T)

然而,當用戶選擇不給繪圖著色時,該函式會為非彩色線生成一個圖例跟蹤,我想在其中顯示的是目標標記圖例。
## render plot
plot_func(plot_color = F)

有誰知道如何解決這一問題?我已經嘗試在每個相應的跟蹤中指定showlegend = T或showlegend = F,但是當我這樣做時,當顏色打開時圖例出現,但當顏色關閉時完全消失。
uj5u.com熱心網友回復:
您需要showlegend通過layout(showlegend = T)以下方式“全域”激活plot_obj:
## libraries
library(tidyr)
library(plotly)
## data
df <- data.frame(grp = c("a", "b"),
val_start = c(1, 2),
val_end = c(5, 6))
df_long <- df %>%
pivot_longer(cols = -grp, names_to = "metric", values_to = "val")
## function
plot_func <- function(plot_color) {
## create main plot object
plot_obj <- df %>%
plot_ly() %>% layout(showlegend = T)
## generate colored/non-colored segments depending on user selection
if(plot_color == T) {
plot_obj <- plot_obj %>%
add_segments(x = ~val_start,
xend = ~val_end,
y = ~grp,
yend = ~grp,
color = ~grp,
colors = c("a" = "red", "b" = "blue"))
} else {
plot_obj <- plot_obj %>%
add_segments(x = ~val_start,
xend = ~val_end,
y = ~grp,
yend = ~grp,
showlegend = F)
}
## generate primary colors
plot_obj %>%
add_markers(inherit = F,
data = df_long,
x = ~val,
y = ~grp,
showlegend = F,
marker = list(color = "green")) %>%
## generate goal marker
add_markers(name = "goal",
x = 4,
y = ~grp,
marker = list(color = "black"))
}
plot_func(plot_color = F)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/384685.html
上一篇:如何在分組密度圖的頂部添加中值?
