R:将多个 html 小部件保存在一起

2023-09-07前端开发问题
18

本文介绍了R:将多个 html 小部件保存在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 R 编程语言.我有兴趣学习如何保存几个html 小部件".一起.我已经能够手动创建不同类型的 html 小部件:

I am using the R programming language. I am interested in learning how to save several "html widgets" together. I have been able to manually create different types of html widgets:

#widget 1
library(htmlwidgets)
library(leaflet)
library(RColorBrewer)

# create map data
map_data <- data.frame(
  "Lati" = c(43.6426, 43.6424, 43.6544, 43.6452, 43.6629), "Longi" = c(-79.3871, -79.3860, -79.3807, -79.3806, -79.3957),
  "Job" = c("Economist", "Economist", "Teacher", "Teacher", "Lawyer"),
  "First_Name" = c("John", "James", "Jack", "Jason", "Jim"),
  "Last_Name" = c("Smith", "Charles", "Henry", "David", "Robert"),
  "vehicle" = c("car", "van", "car", "none", "car")
)

kingdom <- c("Economist", "Lawyer", "Teacher")
my_palette <- brewer.pal(3, "Paired")
factpal <- colorFactor(my_palette, levels = kingdom)

groups <- unique(map_data$Job)

# finalize map
map <- leaflet(map_data) %>%
  addTiles(group = "OpenStreetMap") %>% 
  addCircleMarkers(~Longi, ~Lati, popup = ~Job,
                   radius = 10, weight = 2, opacity = 1, color = ~factpal(Job),
                   fill = TRUE, fillOpacity = 1, group = ~Job
  )

widget_1 = map %>%
  addLayersControl(overlayGroups = groups, options = layersControlOptions(collapsed = FALSE)) %>%
  addTiles() %>%
  addMarkers(lng = ~Longi, 
             lat = ~Lati, 
             popup = ~paste("Job", Job, "<br>", 
                            "First_Name:", First_Name, "<br>", 
                            "Last_Name:", Last_Name, "<br>", "vehicle:", vehicle, "<br>"))

小部件 2:

##### widget 2

library(plotly)
library(ggplot2)

p_plot <- data.frame(frequency = c(rnorm(31, 1), rnorm(31)),
                     is_consumed = factor(round(runif(62))))
p2 <- p_plot %>%
  ggplot(aes(frequency, fill = is_consumed)) +
  geom_density(alpha = 0.5)     

widget_2 = ggplotly(p2)

小部件 3:

#####widget_3

today <- Sys.Date()
tm <- seq(0, 600, by = 10)
x <- today - tm
y <- rnorm(length(x))
widget_3 <- plot_ly(x = ~x, y = ~y, mode = 'lines', text = paste(tm, "days from today"))

小部件 4:

####widget_4

library(igraph)
library(dplyr)
library(visNetwork)


Data_I_Have <- data.frame(
   
    "Node_A" = c("John", "John", "John", "Peter", "Peter", "Peter", "Tim", "Kevin", "Adam", "Adam", "Xavier"),
    "Node_B" = c("Claude", "Peter", "Tim", "Tim", "Claude", "Henry", "Kevin", "Claude", "Tim", "Henry", "Claude")
)


graph_file <- data.frame(Data_I_Have$Node_A, Data_I_Have$Node_B)


colnames(graph_file) <- c("Data_I_Have$Node_A", "Data_I_Have$Node_B")

graph <- graph.data.frame(graph_file, directed=F)
graph <- simplify(graph)


nodes <- data.frame(id = V(graph)$name, title = V(graph)$name)
nodes <- nodes[order(nodes$id, decreasing = F),]
edges <- get.data.frame(graph, what="edges")[1:2]

widget_4 = visNetwork(nodes, edges) %>%   visIgraphLayout(layout = "layout_with_fr") %>%
    visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)

从这里,我发现了另一个 stackoverflow 帖子,其中提出了类似的问题:使用R和plot.ly,如何将多个htmlwidgets保存到我的html中?

From here, I found another stackoverflow post where a similar question was asked: Using R and plot.ly, how to save multiples htmlwidgets to my html?

在这篇文章中,它解释了如何将多个 html 小部件保存在一起 - 回答问题的人编写了一个函数来这样做:

In this post, it explains how to save several html widgets together - the person who answered the question wrote a function to do so:

library(htmltools)
save_tags <- function (tags, file, selfcontained = F, libdir = "./lib") 
{
  if (is.null(libdir)) {
    libdir <- paste(tools::file_path_sans_ext(basename(file)), 
                    "_files", sep = "")
  }
  htmltools::save_html(tags, file = file, libdir = libdir)
  if (selfcontained) {
    if (!htmlwidgets:::pandoc_available()) {
      stop("Saving a widget with selfcontained = TRUE requires pandoc. For details see:
", 
           "https://github.com/rstudio/rmarkdown/blob/master/PANDOC.md")
    }
    htmlwidgets:::pandoc_self_contained_html(file, file)
    unlink(libdir, recursive = TRUE)
  }
  return(htmltools::tags$iframe(src= file, height = "400px", width = "100%", style="border:0;"))
}

我尝试使用此功能将 4 个小部件保存在一起:

I tried using this function to save the 4 widgets together:

save_tags(widget_1, widget_2, widget_3, widget_4)

但是这样做,我得到了以下错误:

But doing so, I got the following error:

 Error in dirname(file) : a character vector argument expected 

有没有一种直接简单的方法可以将多个 html 小部件保存在一起?

Is there a straightforward and simple way for saving multiple html widgets together?

谢谢

注意:我知道您可以在 R 中使用 combineWidgets() 函数:

NOTE: I know that you can use the combineWidgets() function in R:

library(manipulateWidget)
combineWidgets(widget_1, widget_2, widget_3, widget_4)

但是,我使用的计算机没有互联网接入或 USB 端口.这台计算机预装了带有有限库的 R 副本(它包含我的问题中使用的所有库,除了manipulateWidget").我正在寻找将多个 html 小部件保存在一起的最简单方法(例如,这在 base R 中是否可行)?

However, I am working with a computer that has no internet access or USB ports. This computer has a pre-installed copy of R with limited libraries (it has all the libraries used throughout my question except "manipulateWidget"). I am looking for the simplest way to save multiple html widgets together (e.g. is this possible in base R)?

谢谢

推荐答案

如果格式不重要,可以使用tagList合并widget,直接保存:

If format doesn't matter too much, you can merge the widgets using tagList and save them directly:

htmltools::save_html(tagList(widget_1, widget_2, widget_3, widget_4), file = "C://Users//Me//Desktop//widgets.html")

(不用说您需要编辑文件路径!)

(It goes without saying that you will need to edit the filepath!)

如果要控制小部件的布局,可以将每个小部件包装在一个 div 中,然后设置它们的样式:

If you want to control the layout of the widgets, you can wrap each in a div, and then style those:

doc <- htmltools::tagList(
  div(widget_1, style = "float:left;width:50%;"),
  div(widget_2,style = "float:left;width:50%;"),
  div(widget_3, style = "float:left;width:50%;"),
  div(widget_4, style = "float:left;width:50%;")
)

htmltools::save_html(html = doc, file = "C://Users//Me//Desktop//widgets.html")

这篇关于R:将多个 html 小部件保存在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Fatal error: Call to a member function fetch_assoc() on a no
业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass...
2024-12-13 前端开发问题
136

layui实现laydate日历控件控制之前日期不可选择
具体实现代码如下: laydate.render({ elem: '#start_time', min:0, //,type: 'date' //默认,可不填}); 只要加一个min参数,就可以控制了。0表示之前的日期不可...
2024-11-29 前端开发问题
133

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313