【问题标题】:R open plotly in standalone windowR在独立窗口中打开
【发布时间】:2017-05-18 12:53:40
【问题描述】:

我想在独立窗口中显示一个绘图对象,其行为类似于使用基本 R plot() 函数弹出的窗口。

使用 plotly 网站上的一个基本示例:

library(ggplot2)
library(plotly)

d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- ggplot(data = d, aes(x = carat, y = price)) +
     geom_point(aes(text = paste("Clarity:", clarity))) +
     geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)

p2 <- ggplotly(p)

p2 对象是一个htmlwidget 对象,我可以使用sizingPolicy 元素来控制它的显示,如here 所述。但是,我找不到任何可以让我将查看器/浏览器设置为当前浏览器(作为新选项卡)或 RStudio 之外的东西的任何东西。

理想情况下,我希望避免 R 包之外的应用程序从 R 中启动单独的窗口。但是,我也很乐意弄清楚如何精细控制浏览器输出以将 p2 显示为新窗口在展台或应用模式下(有关展台/应用模式的一些示例,请参阅this question 的答案)。

编辑:虽然我在讨论一些我能找到的选项时提到了 RStudio,但我说的是从简单的控制台使用 R。也就是说,粒度显示选项应该希望独立于用户界面。

【问题讨论】:

  • 您是在谈论 R-Studio 中的用法吗?似乎是,但plot 不会在 R-Studio 中打开新窗口。除非有一个我不知道的选项(可能)。为什么在浏览器中显示 htmlwidget 与您要求的不一样?
  • @MikeWise 这将在 R-Studio 之外使用。在浏览器中显示就足够了,如果我可以对该显示进行一些控制——在信息亭或应用程序模式下打开一个新页面。将另一个选项卡添加到我可能打开的 20 个选项卡并将浏览器移动到当前虚拟工作区的默认行为并不是特别方便。
  • 嗯,您可以尝试将另一个扩展名附加到您的文件(就像他们在您的 htmlwidget 链接中 forceNetwork 下的 .svg 所做的那样),将该扩展名注册到您没有的另一个浏览器采用。也许这会让你得到你想要的?
  • @MikeWise 我觉得这有点过头了,但看起来forceNetwork 中的.svg 处理是在JS 中为一个新的小部件定义的。就我而言,我假设所有 JS 都将由 plotly.js 库处理,尽管也许有一种方法可以添加新方法。无论哪种方式,都值得研究更多,谢谢。我还需要弄清楚实际上是什么在调用打开浏览器选项卡,也许看看那里是否有任何可用的选项。

标签: r plotly htmlwidgets


【解决方案1】:

我有一个可行的解决方案,但如果有人有更好的解决方案,我很乐意更改已接受的答案。

我定义了一个打印函数,可用于为htmlwidget 对象启动自定义浏览器命令。在这种情况下,我使用了chromium-browser -app=...,但总体方法应该是通用的。

print_app <- function(widget) {

  # Generate random file name
  temp <- paste(tempfile('plotly'), 'html', sep = '.')

  # Save. Note, leaving selfcontained=TRUE created files that froze my browser
  htmlwidgets::saveWidget(widget, temp, selfcontained = FALSE)

  # Launch with desired application
  system(sprintf("chromium-browser -app=file://%s", temp))

  # Return file name if it's needed for any other purpose
  temp
}

结合前面的例子:

library(ggplot2)
library(plotly)

d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- ggplot(data = d, aes(x = carat, y = price)) +
     geom_point(aes(text = paste("Clarity:", clarity))) +
     geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)

p2 <- ggplotly(p)
print_app(p2)

似乎htmlwidgets 通常使用来自htmltoolshtml_print 函数,而后者又通过getOption("viewer", utils::browseURL) 选择要使用的浏览器,这包含了许多浏览器选择选项——这使得改变。

在本地保存 html 文件的想法来自 plotly 问题:saving plotly plots locally?

【讨论】:

  • 你是怎么运行这个的?与rscript?你用的是什么系统?
  • @MikeWise 我使用的是 Linux(Mint 和 Arch),我通常在基本的交互式 R shell 中运行命令或源脚本。我刚刚检查过,它也适用于 RStudio 和 Rscript。不过不确定是否有任何其他操作系统。
【解决方案2】:

如果您使用的是 MacOS,请在 @ssokolen 的回答中更改此行

 # Launch with desired application
 system(sprintf("chromium-browser -app=file://%s", temp))

 system(sprintf("open -a 'google chrome'  /%s", temp))

使用 Intellij R 插件在 MacOs Catalina 中的 zsh 中工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2014-11-06
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多