【问题标题】:Scatter point click to weblink disabled when ggplot/ggplotly includes annotations or shapes当 ggplot/ggplotly 包含注释或形状时,散点单击到 web 链接被禁用
【发布时间】:2019-01-15 03:55:46
【问题描述】:

我正在使用闪亮的仪表板开发闪亮的应用程序,并试图使绘图点可点击。单击时,应从数据集中的关联 url 列中显示关联的网页。

我正在使用 plotly,将 ggplot 转换为 ggplotly。

不幸的是,我的 ggplot 有注释和形状,这似乎禁用了 htmlwidgets::onRender() 函数。但是,当我没有添加诸如形状和注释之类的美学时, onRender() 似乎可以工作。

任何人都知道如何使下面的代码与注释和形状一起使用?非常感谢您的帮助!

我正在尝试编码的版本:

library(plotly)
library(htmlwidgets)
library(ggplot2)

iris$url <- paste0(
  "http://google.com/#q=", 
  iris$Species
)

p <- ggplot(data = iris, aes(x = Petal.Width, y = Sepal.Length, shape = Species))+
  geom_point()+
  annotate('rect', xmin = 2, xmax = 6, ymin = 2, ymax = 6,fill="firebrick",alpha = .2)
p
p1 <- ggplotly(p)
p1

p1$x$data[[1]]$customdata <- iris$url

#pp  <- add_markers(pp, customdata = ~url)

p2 <- onRender(p1, "
                function(el, x) {
                el.on('plotly_click', function(d) {
                var url = d.points[0].customdata;
                //url
                window.open(url);
                });
                }
                ")
p2

作为上述基础代码的更简单的版本:

library(plotly)
library(htmlwidgets)
library(ggplot2)

iris$url <- paste0(
  "http://google.com/#q=", 
  iris$Species
)

p <- ggplot(data = iris, aes(x = Petal.Width, y = Sepal.Length))+
  geom_point()
p
p1 <- ggplotly(p)
p1

p1$x$data[[1]]$customdata <- iris$url

#pp  <- add_markers(pp, customdata = ~url)

p2 <- onRender(p1, "
                function(el, x) {
                el.on('plotly_click', function(d) {
                var url = d.points[0].customdata;
                //url
                window.open(url);
                });
                }
                ")
p2

【问题讨论】:

    标签: r ggplot2 shiny plotly ggplotly


    【解决方案1】:

    您必须将链接信息添加到要链接的每一层。 这应该有效:

    library(plotly)
    library(htmlwidgets)
    library(ggplot2)
    
    
    
    p <- ggplot(data = iris, aes(x = Petal.Width, y = Sepal.Length, shape = Species))+
      geom_point()+
      annotate('rect', xmin = 2, xmax = 6, ymin = 2, ymax = 6,fill="firebrick",alpha = .2)
    p
    p1 <- ggplotly(p)
    p1
    
    for(i in 1:length(p1$x$data)){
      if(p1$x$data[[i]]$name %in% levels(iris$Species)){
        p1$x$data[[i]]$customdata = rep(paste0("http://google.com/#q=",
        p1$x$data[[i]]$name),length(p1$x$data[[i]]$x))
      }
    }
    
    
    p2 <- onRender(p1, "
                    function(el, x) {
                    el.on('plotly_click', function(d) {
                    var url = d.points[0].customdata;
                    //url
                    window.open(url);
                    });
                    }
                    ")
    p2
    

    它只是遍历 plotly-instance 上的所有层,如果名称与物种名称之一匹配,则添加指向相应 google-query 的链接。

    【讨论】:

    • 有没有办法打开/触发带有图表/表格的模式作为数据子集的钻取?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2019-01-11
    • 2011-07-19
    • 2011-09-23
    • 2019-02-01
    • 2023-03-05
    相关资源
    最近更新 更多