Why is the layout of a graph from visnetwork in html too small - html

When I render the example-Rmd below, it looks like this (with Chrome, not really a difference to Firefox):
The figure is way too small and if I look at the "real" graphs I need, the height is too small and the ratio height-width is even worse.
Here is a reproducible example:
---
title: "Untitled"
author: "author"
date: "9 Mai 2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Example
Here is a line of text...................................................................................................................................................................................................................................................................
```{r echo=FALSE}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:20)
edges <- data.frame(from = sample(c(1:20), 10), to = sample(c(1:20), 10))
visNetwork(nodes, edges, width = "100%", height = "100%") %>%
visNodes() %>%
visOptions(highlightNearest = TRUE) %>%
visInteraction(navigationButtons = TRUE,
dragNodes = FALSE,
dragView = FALSE, zoomView = FALSE) %>%
visEdges(arrows = 'to')
```
Here is another line of text....................................................................................................................................................................................................................................................................

I expected to fix it using some chunk options, such as out.height or fig.height but for some reason they don't.
However you can set a fixed height for the widget itself, simply passing a number to the height argument that will be interpreted as pixels:
```{r echo=FALSE}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:20)
edges <- data.frame(from = sample(c(1:20), 10), to = sample(c(1:20), 10))
visNetwork(nodes, edges, width = "100%", height = 700) %>%
visNodes() %>%
visOptions(highlightNearest = TRUE) %>%
visInteraction(navigationButtons = TRUE,
dragNodes = FALSE,
dragView = FALSE, zoomView = FALSE) %>%
visEdges(arrows = 'to')
```

Related

R: Modifying an R Markdown Tutorial

I am working with the R programming language.
I have the following 8 plots have been made beforehand and saved as HTML files in my working directory:
library(plotly)
Red_A <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
layout(title = 'Red A')
Red_B <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
layout(title = 'Red B')
Blue_A <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
plot_ly(x = ~var1, y = ~var2, marker = list(color = "blue")) %>%
layout(title = 'Blue A')
Blue_B <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
layout(title = 'Blue B')
htmlwidgets::saveWidget(as_widget(Red_A), "Red_A.html")
htmlwidgets::saveWidget(as_widget(Red_B), "Red_B.html")
htmlwidgets::saveWidget(as_widget(Blue_A), "Blue_A.html")
htmlwidgets::saveWidget(as_widget(Blue_B), "Blue_B.html")
My Question: Using this template over here (https://testing-apps.shinyapps.io/flexdashboard-shiny-biclust/) - I would like to make a flexdashboard that allows the user to select (from two dropdown menus) a "color" and a "letter" - and then render one of the corresponding graphs (e.g. col = Red & letter = B -> "Red B"). I would then like to be able to save the final product itself as an HTML file. This would look something like this:
I tried to write the Rmarkdown Code for this problem by adapting the tutorial:
---
title: "Plotly Graph Selector"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
Inputs {.sidebar}
selectInput("Letter", label = h3("Letter"),
choices = list("A" = 1, "B" = 2),
selected = 1)
selectInput("Color", label = h3("Color"),
choices = list("Red" = 1, "Blue" = 2),
selected = 1)
How can I continue with this?
Note
I know that it is possible to load HTML files into a dashboard that have been made beforehand, e.g.
# https://stackoverflow.com/questions/73467711/directly-loading-html-files-in-r
<object class="one" type="text/html" data="Red_A.html"></object>
<object class="one" type="text/html" data="Red_B.html"></object>
<object class="one" type="text/html" data="Blue_A.html"></object>
<object class="one" type="text/html" data="Blue_B.html"></object>
You could use iframe with renderUI to render the HTML files locally using addResourcePath with the location of your files. With paste0 and paste your could dynamically create the html files to select them. Here is some reproducible code:
---
title: "Plotly Graph Selector"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
self_contained: false
runtime: shiny
---
```{r global, include=FALSE}
```
Inputs {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("Letter", label = h3("Letter"),
choices = c("A", "B"),
selected = "A")
selectInput("Color", label = h3("Color"),
choices = c("Red", "Blue"),
selected = "Red")
```
Row
-----------------------------------------------------------------------
```{r}
addResourcePath("Downloads", "~/Downloads")
renderUI({
color <- input$Color
letter <- input$Letter
tags$iframe(
seamless="seamless",
src=paste0("Downloads/", paste0(paste(color, letter, sep = "_"), ".html")),
width = 600,
height = 400)
})
```
Output:
If you want to remove the border around the plot, you could add frameBorder = "0" in your iframe call like this:
```{r}
addResourcePath("Downloads", "~/Downloads")
renderUI({
color <- input$Color
letter <- input$Letter
tags$iframe(
seamless="seamless",
src=paste0("Downloads/", paste0(paste(color, letter, sep = "_"), ".html")),
width = 600,
height = 400,
frameBorder = "0")
})
```
Output:
Using getwd() with basename like this:
```{r}
addResourcePath(basename(getwd()), getwd())
renderUI({
color <- input$Color
letter <- input$Letter
tags$iframe(
seamless="seamless",
src=paste0(basename(getwd()), "/", paste0(paste(color, letter, sep = "_"), ".html")),
width = 600,
height = 400,
frameBorder = "0")
})
```

R markdown table loop NULL outcome

My code is producing a lot of NULLs at the end in the html output.
Could you please help me to prevent it?
---
title: "Test"
output: html_document
---
```{r warning=FALSE, message=FALSE, results = 'asis',echo=FALSE}
library(tidyverse)
library(knitr)
library(kableExtra)
# nest all data except the cut column and create html tables
diamonds_tab <- diamonds %>%
nest(-cut) %>%
mutate(tab = map2(cut,data,function(cut,data){
writeLines(landscape(kable_styling(kable(as.data.frame(head(data)),
caption =cut,
format = "html",align = "c",row.names = FALSE),
latex_options = c("striped"), full_width = T)))
}))
# print tab column, which contains the html tables
invisible(walk(diamonds_tab$tab, print))
```
Instead of using invisible, wrap the print command with capture.output.
---
title: "Test"
output: html_document
---
```{r warning=FALSE, message=FALSE, results = 'asis',echo=FALSE}
library(tidyverse)
library(knitr)
library(kableExtra)
# nest all data except the cut column and create html tables
diamonds_tab <- diamonds %>%
nest(-cut) %>%
mutate(tab = map2(cut,data,function(cut,data){
writeLines(landscape(kable_styling(kable(as.data.frame(head(data)),
caption =cut,
format = "html",align = "c",row.names = FALSE),
latex_options = c("striped"), full_width = T)))
}))
# print tab column, which contains the html tables
walk(diamonds_tab$tab, ~ capture.output(print(.x)))
```
I found out, that it is only enough to remove the walk.

Table title on a different page when using a flextable object in a officedown document

I'm trying to put together a document where a "Tables" section will be found at the end of it. There, all the tables that I will have cited throughout the document will be shown.
My problem is that whenever I have a long table spanning several pages, the table title is left alone on one page and the table follows on the next page. This occurs in both portrait and landscape mode.
My question is: What Can I do with that so that table titles are found just above their associated tables, on the same page?
Here is a snapshot of the problem:
In portrait mode, the table is ok when showing only the first few lines (using the r head() function, left), while the whole table is incorrect (two pages on the right).
The same applies in landscape mode.
And here is the reproducible example.
```
---
output: officedown::rdocx_document
---
```
```{r setup, echo=F, message=F, warning=F}
knitr::opts_chunk$set(echo = F,
collapse = T,
fig.align = "center",
fig.width = 6,
fig.height = 8,
fig.cap = T,
fig.pos = "!h",
message = F,
warning = F)
library(magrittr) # for using the %>%
library(dplyr)
library(officedown)
library(officer)
library(flextable)
# portrait section
portrait <- prop_section(type = "continuous")
# landscape section
landscape <- prop_section(page_size = page_size(orient = "landscape"), type = "continuous")
# Function for setting widths
FitFlextableToPage <- function(ft, pgwidth = 6){
ft_out <- ft %>% autofit()
ft_out <- width(ft_out, width = dim(ft_out)$widths*pgwidth /(flextable_dim(ft_out)$widths))
return(ft_out)
}
set.seed(12345) # for reproducibility when setting table1
```
```{r, echo = F}
# Creation of table1
years <- 1990:2022
table1 <- tibble(year = years,
dat1 = sample(rnorm(n = 1000, 0, 2), size = length(years), replace = T)) %>%
mutate(year = as.character(year),
dat2 = dat1 * 10,
dat3 = dat1 * 1000)
#table1
```
# portrait table
```{r}
foot <- "Preliminary data." # footnote
col_names <- c("Year", "Column 1", "Column 2", "Column 3") # table headers
# Setting the footnote
cor <- which(with(table1, year %in% 2021:2022))
# length(cor) # 2
# Headers
names(table1) <- col_names
```
```{r table1, tab.cap = "Header of table1 in portrait style."}
table1 %>% head() %>% flextable() %>% autofit()
```
\newpage
```{r table2, tab.cap = "All of table1 in portrait style + footnote."}
table1 %>%
flextable() %>%
footnote(i = cor, j = 1, value = as_paragraph(foot),
ref_symbols = "a", part = "body")
block_section(portrait) # end of portrait section
```
# landscape table
Let's put these same tables on a landscape page.
```{r table3, tab.cap = "Header of table1 in landscape style."}
table1 %>% head() %>% flextable() %>% autofit()
```
\newpage
```{r table4, tab.cap = "All of table1 in landscape style + footnote."}
table1 %>%
flextable() %>%
footnote(i = cor, j = 1, value = as_paragraph(foot),
ref_symbols = "a", part = "body") %>%
FitFlextableToPage(pgwidth = 9.5)
block_section(landscape) # end of landscape section
```
# New section in portrait style
bla bla bla.
As David Gohel kindly replied, the chunk option ft.keepnext was the key here and needed to be set to FALSE in the example. This was done by adding an extra argument in the opts_chunk$set() at the beginning of the script, such as:
knitr::opts_chunk$set(echo = F,
collapse = T,
fig.align = "center",
fig.width = 6,
fig.height = 8,
fig.cap = T,
fig.pos = "!h",
message = F,
warning = F,
ft.keepnext = F) # the argument added

How to combine datatable and HTML in renderUI when developing a FlexdashBoard app.?

I am sure that no one helped me, tk. I just asked the question not very correctly earlier.
I am trying to create a FlexDashcoard application. To understand how the program works, you need the sample data files that I have prepared. I apologize in advance for the Russian characters in the files, they are presented to you "as is".
Here is my code:
---
title: "AFEA of Russian enterprises"
output:
flexdashboard::flex_dashboard:
storyboard: true
orientation: rows
vertical_layout: fill
theme: simplex
runtime: shiny
---
```{r GlobalOptions}
options(knitr.duplicate.label = 'allow')
rv <- reactiveValues(txt_file = FALSE)
OKVEDselectInputChoices<- reactiveValues(data = NULL)
```
```{r setup, include=FALSE, echo=FALSE, message=FALSE}
### Library connection module ###
library("flexdashboard")
library("dygraphs")
library("shiny")
library("shinyFiles")
library("DT")
library("ggplot2")
library("dplyr")
library("here")
library("data.table")
library("plyr")
### ----------------------------- ###
```
## Sidebar {.sidebar}
```{r}
roots <- c('C' = 'C:/', 'D' = 'D:/', '//' = '\\\\ns\\Public\\Power BI')
renderUI({
shinyFilesButton("files_choose", "Select files", "",
multiple=TRUE,
buttonType = "default",
class = NULL,
icon = icon("list-alt"),
style = "background-image: linear-gradient(#D9230F, #D9230F 6%, #D9230F);
border-color: #A91B0C;
margin-top: 10px;
width: 100%;
float: left;
box-sizing: border-box;",
viewtype = "detail"
)
})
br()
renderUI({
actionButton(inputId = "apply",
label = "Apply",
icon = icon("play"),
style = "background-image: linear-gradient(#D9230F, #D9230F 6%, #D9230F);
border-color: #A91B0C;
margin-top: 10px;
margin-bottom: 10px;
width: 100%;
float: left;
box-sizing: border-box;"
)
})
br()
renderUI({h6(inputId="sideBarText2", "Выбор ОКВЭД(ов):")})
renderUI({
selectInput("OKVEDlectInput",
label = NULL,
choices = OKVEDselectInputChoices$data,
#selected = "Percent White")
multiple=TRUE
)
})
```
```{r}
shinyFileChoose(input, "files_choose",
roots=roots,
filetypes=c('csv'))
rv_result <- eventReactive(
input$apply,{
if (!is.null(input$files_choose))
{
myInputFile <- parseFilePaths(roots,input$files_choose)$datapath
all.files <- myInputFile
print(all.files)
a.vector <- grep("data\\-\\d+\\-structure\\-", all.files, ignore.case = TRUE)
print(a.vector)
all.files <- all.files[a.vector]
all.files<- sort(all.files)
n <- length(all.files)
print(n)
data = vector('list', n)
if (n>0) {
for (i in 2:(n+1)) {
#print(paste("Вот такой файл:" , all.files[i-1]))
data[i-1] <- lapply(all.files[i-1],
fread,
showProgress = TRUE,
sep = ";",
quote = "",
header = FALSE,
stringsAsFactors=TRUE,
select = c(1:124))
}
}
}
table <- rbindlist(data)
UN <- unique(table[[5]])
UN <- sort(UN)
OKVEDselectInputChoices$data <- UN
rv$txt_file <- table
rv_result <- rv$txt_file
#View(rv$txt_file)
}
)
```
### Basic information
```{r}
#renderTable({
# dataset <- rv_result()
# dataset
#})
f <- function(verlist, list_for_ver, resulttyp=0,delna=1) {
# verlist - массив, который требуется проверить на совпадение с элементами второго массива
# list_for_ver - проверочный массив, т.е. тот, с которым сравнимается
# resulttyp (0 - выводятся номера элементов list_for_ver, которые найдены);
# (1 - выводятся найденные значения)
# delna - (0 -если элемент не найде, то он не показывается)
# (1 -если элемент не найде, то указывается NA)
listforreturn <- vector(mode = 'list', length=0)
if ((class(verlist)=='list') && (class(list_for_ver)=='list')){
if (delna==1){
listforreturn <- as.vector(na.omit(match(verlist,list_for_ver)))
}
else{
listforreturn <- as.vector(match(verlist,list_for_ver))
}
if (resulttyp==0){
listforreturn <- as.list(listforreturn)
}
else{
listforreturn<- as.list(list_for_ver[listforreturn])
}
}
return(listforreturn)
}
dataset <- reactive({rv_result()})
renderUI({
data <- dataset()
if (is.null(input$OKVEDlectInput)) {
data <- dataset()
}
else{
d1 <- as.list(input$OKVEDlectInput)
d2 <- as.list(as.vector(data$V5))
result <- which(!is.na(f(d2, d1,0,0)))
result <- as.vector(result)
data <- data[result,]
}
div(HTML("География анлиза насчитывает "),
datatable(data, fillContainer=getOption("DT.fillContainer", TRUE)))
})
```
### Secondary information
Some commentary about Frame 2.
You can download the finished version of the code
My application first creates an interface, allows the user to select a file to import (or several), but with a specific name, and loads these data into the application.
On this line, I create a mapping:
div(HTML("География анлиза насчитывает "),
datatable(data, fillContainer=getOption("DT.fillContainer", TRUE)))
It looks strange. If not addfillContainer=getOption("DT.fillContainer", TRUE), then the scroll bar disappears from the table. When you add this element, everything shrinks to a very narrow size:
I am unable to stretch the table to the bottom for the rest of the free space.
I specially prepared a short version of the code, from which the problem is kind and easy to repeat using a ready-made data array.
---
title: "AFEA of Russian enterprises"
output:
flexdashboard::flex_dashboard:
storyboard: true
orientation: rows
vertical_layout: fill
theme: simplex
runtime: shiny
---
```{r setup, include=FALSE, echo=FALSE, message=FALSE}
library("flexdashboard")
library("DT")
```
## Sidebar {.sidebar}
-------------------------------------
```{r}
```
### Chart A
```{r}
renderUI({
data <- iris
div(HTML("География анлиза насчитывает "),
datatable(data, fillContainer=getOption("DT.fillContainer", TRUE)))
})
```
You can use css to increase/decrease width and height of datatable. I have added style = "height: 175%" in div to increase the height.
---
title: "AFEA of Russian enterprises"
output:
flexdashboard::flex_dashboard:
storyboard: true
orientation: rows
vertical_layout: fill
theme: simplex
runtime: shiny
---
```{r setup, include=FALSE, echo=FALSE, message=FALSE}
library("flexdashboard")
library("DT")
```
## Sidebar {.sidebar}
-------------------------------------
```{r}
```
### Chart A
```{r}
renderUI({
data <- iris
div(HTML("География анлиза насчитывает "),
datatable(data, fillContainer=getOption("DT.fillContainer", TRUE)), style = "height: 175%")
})
```

Is there a way to eliminate y scrollers on shiny output in rmarkdown?

I have an interactive doc in rmarkdown using shiny apps.
My YAML:
---
title: "Shiny HTML Doc"
author: "theforestecologist"
date: "Apr 13, 2017"
output: html_document
runtime: shiny
---
I generate a number of shiny apps throughout this document, but they all are too long (i.e., they all require y scrollers to view their entirety.
I know I can add options = list(height = ###,width = ###) within the shinyApp function in my code chunk to control individual rendered apps, but I want my readers to see my shiny code (sans messy option controls).
So my desired approach is to control all of the shiny app outputs at once.
Specifically, is there a way to make it so they each can have variable heights, but each one be fully pictured (i.e., not needing a vertical (y) scroller)?
Example Code:
---
title: "Shiny HTML Doc"
author: "theforestecologist"
date: "Apr 13, 2017"
output: html_document
runtime: shiny
---
I have an interactive shiny doc with app outputs of varying heights.
By default, they all have the same height, which is too small of a value
(and thus creates the need for vertical scrolling bars).
##### **Example 1**
```{r, eval=TRUE,echo=FALSE}
library(shiny)
ui <- fluidPage(
titlePanel("Ex1"),
sidebarLayout(
sidebarPanel(
checkboxGroupInput(inputId = "type", label = "Plant Type", choices = levels(CO2$Type),
selected = levels(CO2$Type))
),
mainPanel(
plotOutput(outputId = "scatter.plot")
)
)
)
server <- function(input, output) {
output$scatter.plot <- renderPlot({
plot(uptake ~ conc, data = CO2, type = "n")
points(uptake ~ conc, data = CO2[CO2$Type %in% c(input$type),])
title(main = "Plant Trends")
})
}
shinyApp(ui = ui, server = server)
```
The output of the next example is longer and therefore needs a larger height assignment to get rid of the scroll bar.
##### **Example 2**
```{r, eval=TRUE,echo=FALSE}
ui <- fluidPage(
titlePanel("Ex1"),
sidebarLayout(
sidebarPanel(
div(style = "padding:0px 0px 450px 0px;",
checkboxGroupInput(inputId = "type", label = "Plant Type", choices = levels(CO2$Type),
selected = levels(CO2$Type))
)
),
mainPanel(
plotOutput(outputId = "scatter.plot")
)
)
)
server <- function(input, output) {
output$scatter.plot <- renderPlot({
plot(uptake ~ conc, data = CO2, type = "n")
points(uptake ~ conc, data = CO2[CO2$Type %in% c(input$type),])
title(main = "Plant Trends")
})
}
shinyApp(ui = ui, server = server)
```