我有一个函数,可以使用 Plotly for R 中的子图使用公共共享 x 变量来绘制多个 y 变量。我在这里遇到的问题是悬停数据不显示所有图的 y 值;它仅显示鼠标悬停的图形。换句话说,我想链接所有这些图表,以便同时显示所有图表的 y 值。这是代码和输出。显示变量 a 的 y 值;我还想同时查看变量 b 和 c 的 y 值
library(plotly)
library(tidyverse)
plotly_stacked <- function(df, x_colName, cols){
DF <- df[, cols] %>%
tidyr::gather(variable, value, -x_colName ) %>%
transform(id = as.integer(factor(variable)))
DF$variable<- factor( DF$variable, levels = unique( DF$variable))
p <- plot_ly(data = DF, x = ~get(names(DF[1])) , y = ~value, color = ~variable, colors = "Dark2",
yaxis = ~paste0( "y",sort(id, decreasing = F))) %>%
add_lines() %>%
layout(
xaxis = list(
title = ""),
legend = list(
orientation = "h",
xanchor = "center",
x = 0.5)) %>%
plotly::subplot(nrows = length(unique(DF$variable)), shareX = TRUE)
return(p)
}
df <- data.frame(
Time = c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,
1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2),
a = c(0.01,0.02,0.03,0.04,0.05,0.06,0.07,
0.08,0.09,0.1,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18,
0.19,0.2),
b = c(0.001,0.002,0.003,0.004,0.005,0.006,
0.007,0.008,0.009,0.01,0.011,0.012,0.013,0.014,0.015,
0.016,0.017,0.018,0.019,0.02),
c = c(1e-04,2e-04,3e-04,4e-04,5e-04,6e-04,
7e-04,8e-04,9e-04,0.001,0.0011,0.0012,0.0013,0.0014,
0.0015,0.0016,0.0017,0.0018,0.0019,0.002)
)
plotly_stacked(df, "Time", c( "Time" ,"a", "b", "c"))
实现所需结果的一个选项是使用自定义事件处理程序,可以通过
htmlwidgets::onRender
将其应用于绘图。请参阅plotly 书的第五部分了解介绍。
library(plotly)
plotly_stacked(df, "Time", c("Time", "a", "b", "c")) |>
htmlwidgets::onRender("function(el, x){el.on('plotly_hover', function(d) {
var points = d.points[0], pointNum = points.pointNumber;
Plotly.Fx.hover(el.id, [
{ curveNumber: 0, pointNumber: pointNum },
{ curveNumber: 1, pointNumber: pointNum },
{ curveNumber: 2, pointNumber: pointNum }],
['xy', 'xy2', 'xy3']
);
})}")