How do I stop a chart from showing on R markdown? - r

Aims
I have got the ouput that I want i.e. an interactive tree map. Yet, the R Markdown output also shows the static tree map, which I do not want to include.
I also want to adjust the font size on the interactive chart. I know how to adjust the font sizes of the labels in the static diagram using "fontsize.labels", but this does not affect the interactive tree map.
Reprex
---
title: "Untitled"
date: "03/05/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r pressure, echo=FALSE}
library(treemap)
library(d3treeR)
# dataset
group <- c(rep("group-1",4),rep("group-2",2),rep("group-3",3))
subgroup <- paste("subgroup" , c(1,2,3,4,1,2,1,2,3), sep="-")
value <- c(13,5,22,12,11,7,3,1,23)
data <- data.frame(group,subgroup,value)
# basic treemap
p <- treemap(data,
index=c("group","subgroup"),
vSize="value",
type="index",
palette = "Set2",
bg.labels=c("white"),
align.labels=list(
c("center", "center"),
c("right", "bottom")
)
)
# make it interactive ("rootname" becomes the title of the plot):
inter <- d3tree2( p , rootname = "General" )
inter
Output
How do I get rid of the top static tree map?
How do I increase the font size in the interactive tree map?
If you can only answer one of the questions, please do.

Related

Assign figure caption to html widget (vtree package) in R markdown output

I need to implement a figure caption in a plot that is generated by the vtree package in R markdown. I learned that this is a htmlwidget and figure captions should now be possible for htmlwidgets used in R markdown with install.packages('webshot') and webshot::install_phantomjs() (reference: https://bookdown.org/yihui/bookdown/html-widgets.html#ref-R-DT.
But days after I am not really any step further. I did not find any example (show case) for this issue (fig.cap for htmlwidgets in R markdown in the net) so my hope is that someone out there can give me some help!
In my iris dataset example, in Fig. 1 the caption is not working in contrast to Fig. 2.
my iris set example RMD file:
YAML
---
title: "test"
author: "TJ"
date: "14 12 2020"
output: html_document
---
code chunk 1: load libraries and data
knitr::opts_chunk$set(echo = TRUE)
library(vtree)
library(webshot)
library(tidyverse)
attach(iris)
df <- iris %>%
select(Species) %>%
cbind(sapply(levels(.$Species), `==`, .$Species))
code chunk 2: Figure 1
{r fig1, echo=FALSE, fig.cap="Vtree plot"}
vtree(iris, "Species")
code chunk 3: Figure 2
{r fig2, echo=FALSE, fig.cap="Scatter plot iris dataset"}
plot(Sepal.Length, Sepal.Width, main="Scatterplot Example",
xlab="Sepal Length ", ylab="Sepal Width ", pch=19)
There is a workaround using the Magick package.You save the image as .png using grVizToPNG (make sure you comment this line out before you render your document or put it in a separate chunk with ยด{r eval = FALSE}, otherwise you will get an error during rendering:
```{r eval=FALSE, echo = FALSE}
myimage <- vtree(iris, "Species")
saveMyimage <- grVizToPNG(myimage, width=800)
```
Here you use the Magickpackage:
```{r magick, echo= FALSE}
MyimagePNG <- image_read("myimage.png")
image_annotate(MyimagePNG, "Vtree plot", size = 35, gravity = "southwest")
```

Dynamic plots and tables inside Rmarkdown

I am new to Rmarkdown and shiny and forgive me for some naive questions. I have build a code in two parts first where I do all the processing and second where I call the Rmarkdown to knit it.
The first code example.R is as follows and works fine independently (with only glitch of plots being trimmed from sides):
# Create a label for the knitr code chunk name
## #knitr ExternalCodeChunk020
library(Seurat)
library(tidyverse)
library(sleepwalk)
library(gridExtra)
library(plotly)
library(DT)
# Set up some sample data
data(mtcars)
# Display the xvars
# Note that I don't really want to display the xvars, but this line is included
# to demonstrate that text output won't show up in the RMarkdown in this example.
a <- ggplotly(ggplot(mtcars, aes(cyl,mpg)) + geom_boxplot())
b <- ggplotly(ggplot(mtcars, aes(wt,mpg)) + geom_point())
subplot(a, b, nrows=1)
DT::datatable(mtcars, class = "cell-border stripe", rownames = FALSE, filter ="top",
editable =TRUE, extension = "Buttons", options = list(dom="Bfrtip",
buttons =c("copy", "csv", "excel", "pdf","print")))
ggplotly(ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5))
# Display the date and time
# Similar to xvars above, this line is intended to demonstrate that text output
# won't be displayed in this RMarkdown example.
Sys.Date()
The second part of the code (mrkdwn.Rmd) is where I try to knit and generate Rmarkdown report:
---
title: "Code Chunks"
author: "Author"
date: "November 13, 2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::read_chunk("example.R")
```
This first code chunk prints the externally located code,
but it does not execute the code. The next code chunk
executes the externally located code, but it does not print code
itself. Text output is suppressed, and figures are plotted,
but only after all of the code is executed.
```{r DisplayCodeChunk, eval = FALSE, echo = FALSE}
<<ExternalCodeChunk020>>
```
```{r RunCodeChunk, echo = FALSE, eval = TRUE, results = 'hide'}
<<ExternalCodeChunk020>>
```
the output doesn't contain plots. I am not sure what is going wrong, could anyone of you help me in fixing this.
I know that an easy fix is to put both parts of the code together inside the Rmarkdown like this:
---
title: "test3"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
library(Seurat)
library(tidyverse)
library(sleepwalk)
library(gridExtra)
library(plotly)
library(DT)
# Set up some sample data
data(mtcars)
# Display the xvars
# Note that I don't really want to display the xvars, but this line is included
# to demonstrate that text output won't show up in the RMarkdown in this example.
a <- ggplotly(ggplot(mtcars, aes(cyl,mpg)) + geom_boxplot())
b <- ggplotly(ggplot(mtcars, aes(wt,mpg)) + geom_point())
subplot(a, b, nrows=1)
DT::datatable(mtcars, class = "cell-border stripe", rownames = FALSE, filter ="top",
editable =TRUE, extension = "Buttons", options = list(dom="Bfrtip",
buttons =c("copy", "csv", "excel", "pdf","print")))
ggplotly(ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5))
# Display the date and time
# Similar to xvars above, this line is intended to demonstrate that text output
# won't be displayed in this RMarkdown example.
Sys.Date()
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Since I need to process large datasets and generate graphs/plots and table I would prefer to keep them separately, so that my Rmarkdown doesn't crash. May be this is wrong and there could be a better approach, please suggest.
Many thanks for your time and help.

Rayshader in Rmarkdown file?

When I render a Rayshader graphic, it pops open Xquartz on my mac, no problem, but what if I wanted to include it in my Rmarkdown document, it just shows the code, no graphic? I understand this is a heavy graphic intensive render, but looking for any tips. thanks, below is my code:
---
title: "rayshader"
author: "Daniel"
date: "6/16/2020"
output:
html_document:
self_contained: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r cars}
library(rayshader)
#Here, I load a map with the raster package.
loadzip = tempfile()
download.file("https://tylermw.com/data/dem_01.tif.zip", loadzip)
localtif = raster::raster(unzip(loadzip, "dem_01.tif"))
unlink(loadzip)
#And convert it to a matrix:
elmat = raster_to_matrix(localtif)
elmat %>%
sphere_shade(texture = "desert") %>%
add_water(detect_water(elmat), color = "desert") %>%
add_shadow(ray_shade(elmat, zscale = 3), 0.5) %>%
add_shadow(ambient_shade(elmat), 0) %>%
plot_3d(elmat, zscale = 10, fov = 0, theta = 135, zoom = 0.75, phi = 45, windowsize = c(1000, 800))
```
From the package owner:
To embed the plot into an RMarkdown document, you need to call rgl::rglwidget() after bringing up your plot. If you're embedding multiple plots, you will also have to close to previous plot using rgl::rgl.close() before plotting the next one.
reference
Worked for me.
Try adding this to the end of your code:
Sys.sleep(0.2)
render_snapshot()
I am able to generate interactive .HTML files of rayshader's 3D renders through the following approach in an R Markdown, using RStudio:
title: "title"
author: "author"
date: "date"
output: html_document
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(rayshader)
library(MetBrewer)
library(tidyverse)
library(rgl)
knitr::knit_hooks$set(webgl = hook_webgl)
The key to embedding the 3D render is on the hook_webgl() function in knitr. The issue is discussed in more length in this thread:
including a interactive 3D figure with knitr
, including a reference to the alternative writeWebGL() function.

Problems with simultaneous use Sankey and d3tree htmlwidgets on R Notebook?

I use R notebook for data analysis report.
I want to render Sankey and d3tree htmlwidgets on R notebook simultaneously.
I put snakey and then d3tree example code in r chunk, output is well printed on rstudio.
When I entered preview button, sankey output well appeared on html.
But, d3tree output doesn't render on html.
I tryed that put d3tree and then sankey. the result is that two of d3tree and sankey dosen't render on html.
what is the problem??
Can i solve these?
the example code like below
---
title: "test"
output: html_notebook
---
```{r, echo=FALSE}
library(networkD3)
library(treemap)
library(d3treeR)
```
```{r, echo=FALSE}
net_cycles <- list(
links = data.frame(
source = c(0,0,0,1,1,5),
target = c(1,2,3,4,5,0),
value = 10
),
nodes = data.frame(
name = letters[1:6]
)
)
```
```{r, echo=FALSE}
data(business)
business$employees.growth <- business$employees - business$employees.prev
tree <- treemap(business,
index=c("NACE1", "NACE2"),
vSize="employees",
vColor="employees.growth",
type="value",
palette="-RdGy",
range=c(-30000,30000))
```
```{r}
sankeyNetwork(
net_cycles$links,
net_cycles$nodes,
Value = "value"
)
d3tree2(
# Brewer's Red-White-Grey palette reversed with predefined range
tree
,rootname = "World"
)
```

Controlling the size and number of graphs per pdf page generated by ggplot loop in R markdown

I would like to generate a pdf document, using R markdown, to display a series of plots made using ggplot in a for loop. Is it possible to control number of plots on each page so there is, for example, a 2 X 2 grid of plots per page?
I'd like to maintain the flexibility so that I can change the total number of graphs, so that it splits across the appropriate number of pages.
My attempt using ggplot2 and gridExtra packages is below, but I can't control the number of graphs per page, it seems to want to squeeze them on to a sinlge page only. I've tried changing the ncol,nrow,heights,widths arguments in grid.arrange but it doesn't seem to help.
---
title: "ggplot Layout"
output: pdf_document
---
```{r,figure2 fig.height=8, fig.width=6,echo=FALSE,message=FALSE}
library(ggplot2)
library(gridExtra)
graphlist<-list()
count <- 1
colnums<-c(1,5,6,7,8,9,10)
for (i in colnums) {
plot.x.name<-names(diamonds[i])
p <- ggplot(data=diamonds,aes_string(x = plot.x.name)) + geom_histogram()
graphlist[[count]]<-p
count <- count+1
}
do.call("grid.arrange",c(graphlist,ncol=2))
```
The type of thing I'm looking for is demonstrated by this code (adapted from
http://kbroman.github.io/knitr_knutshell/pages/figs_tables.html), but this doesn't work with ggplot, unfortunately.
---
title: "Example Layout"
output: pdf_document
---
```{r bunch_o_figs,fig.height=8, fig.width=6, message=FALSE,echo=FALSE}
n <- 100
x <- rnorm(n)
par(mfrow=c(2,2), las=1)
for(i in 1:20) {
y <- i*x + rnorm(n)
plot(x, y, main=i)
}
``
You could try marrangeGrob
---
title: "ggplot Layout"
output: pdf_document
---
```{r figure2 , fig.height=8, fig.width=6,echo=FALSE,message=FALSE}
library(ggplot2)
library(gridExtra)
graphlist <- replicate(10, qplot(1,1), simplify = FALSE)
do.call("marrangeGrob",c(graphlist,ncol=2,nrow=2))
```

Resources