The section of the bookdown manual on generating figures demonstrates a case where include_graphics() can be given a vector of paths of length > 1, producing a number of subplots with a single caption:
However, when I try this in my fork of thesisdown, in the PDF output I get the figure caption (and, judging by the spacing, the entire figure environment) repeated for each subplot. Here is a reproducible example:
---
output: bookdown::pdf_document2
toc: false
---
```{r, echo = FALSE}
for(i in 1:3){
jpeg(filename = paste0("temp_", i, ".jpg"), width = 600, height = 250)
plot(cars)
title(main = i)
dev.off()
}
```
```{r fig.cap = "Caption", out.width="100%", fig.ncol = 1, echo = FALSE}
knitr::include_graphics(paste0("temp_", 1:3, ".jpg"))
```
I was hoping more for the five images stacked, with a single caption at the bottom. This also appears to be breaking the figure cross-referencing, as each plot has its own figure number and cross-references to the chunk render as ??.
Getting subfigures requires a few additional settings to be set in the chunk header.
fig.subcap is a list of the captions for subfigures
fig.ncol: the number of columns of subfigures
out.width: the output width of the figures. You will normally set this 100% divided by the number of sub columns.
Subfigures are built using the subfig package. You can either include this within your LaTeX bookdown template, or alternative you can added it to the YAML as follows:
Here is an example:
---
output: bookdown::pdf_document2
toc: false
header-includes:
- \usepackage{subfig}
---
```{r, echo = FALSE}
for(i in 1:3){
jpeg(filename = paste0("temp_", i, ".jpg"), width = 600, height = 250)
plot(cars)
title(main = i)
dev.off()
}
```
```{r fig.cap = "Caption", out.width="100%", fig.ncol = 1, echo = FALSE, fig.subcap= c("First", "Second", "Third")}
knitr::include_graphics(paste0("temp_", 1:3, ".jpg"))
```
Related
I would like do add an icon to the text in one of the slides.
I've tried a few things but the end result is unstable. The icon are being printed in the html file, but If I add a slide or some text the the icons dissapear. Even if I revert what I've done with Ctrl+Z to previous working code the icons don't get printed...
I might be missing something, but the bookdown documentation didn't have anything on the subject...
---
title: 'Title'
author: "Author"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output:
ioslides_presentation:
self_contained: true
incremental: false
---
```{r knitr_init, echo=FALSE, message=FALSE, warning=FALSE, cache=FALSE}
## Global options
library(knitr)
library(shiny)
opts_chunk$set(
cache = FALSE,
prompt = FALSE,
tidy = FALSE,
comment = NA,
message = FALSE,
warning = FALSE
)
library(tidyverse)
library(plotly)
```
## S1
`r shiny::tags$i(class = "fa fa-arrow-down",style = "color: rgb(0,166,90)")`
item 3
`r shiny::tags$i(class = "fa fa-arrow-down",style = "color: rgb(0,166,90)")`
item 2
## S2
```{r, echo=F}
data.frame(a=1:10, b=1:10) %>%
plot_ly(x=~a,y=~b)
```
Writing the icons as <i class="fa fa-arrow-down" style="color: rgb(0,166,90)"></i> didn't seem to work either.
One option is to use the package icon (more information here).
---
title: 'Title'
author: "Author"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output:
ioslides_presentation:
self_contained: true
incremental: false
---
```{r knitr_init, echo=FALSE, message=FALSE, warning=FALSE, cache=FALSE}
## Global options
library(knitr)
library(shiny)
opts_chunk$set(
cache = FALSE,
prompt = FALSE,
tidy = FALSE,
comment = NA,
message = FALSE,
warning = FALSE,
echo=FALSE
)
library(tidyverse)
library(plotly)
library(icon)
```
## S1
```{r icon-style1}
icon_style(fontawesome("arrow-down", style = "solid"), scale = 2, fill = "#00A65A")
```
item 3
```{r icon-style2}
icon_style(fontawesome("arrow-down", style = "solid"), scale = 2, fill = "#00A65A")
```
item 2
## S2
```{r, echo=F}
data.frame(a=1:10, b=1:10) %>%
plot_ly(x=~a,y=~b)
```
-output
I just added two code chunks, one for each icon. Additionally, in your first r chunk, I added echo=FALSE to the opts_chunk$set and library(icon). In order to achieve the RGB color you chose, the HEX code was needed (#00A65A).
I am using rmarkdown to print a model -
```{R ForestModel, echo = FALSE, out.width = "100%"}
print(forest_model(res.cox))
```
and getting
Where what I want to get is:
Solved by treating as figure with
```{R Fig1_ForestModel, echo = FALSE, fig.width = 10, fig.asp = .50}
print(forest_model(res.cox))
```
On a R markdown file, does someone know why out.width,out.height,figure.width and figure.height parameters doesn't change plotly charts size when producing a pdf file? ( I precise that such parameters works perfectly using plot function)
Please find below a reproductible example with a Rmarkdown file
On this example, I would like the plotly chart to occupy the entire sheet like the plot chart.
---
title: "Change chart size chart on pdf file using plotly"
output:
pdf_document: default
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo=FALSE,message=FALSE)
```
## Parameters doesn't work with plotly
```{r, out.width='100%',out.height='100%',fig.height=20, fig.width=15, fig.align="left"}
library(plotly)
plot_ly(x = cars[1:10,]$speed,y = cars[1:10,]$dist)
```
## Parameters works using plot function
```{r,out.width='130%',out.height='100%', fig.height=20, fig.width=15, fig.align="left"}
plot(cars[1:10,])
```
Plotly graphs are primarily designed for interactive outputs, and as such, can behave a bit strange when being exported to static images in PDF. This issue has had some similar posts in the past, and appears to come from how webshot creates the static image.
You can fix this by forcing the plotly graph dimensions when creating the graph. The plot_ly function has the arguments width and height which let you set the output dimensions of the resulting plot.
If you want to include HTML objects in PDF reports, you can use the webshot package which essentially takes a screenshot of the rendered plots and converts it into a static image for you to include in the report. This is explained well in the bookdown book. To install it, you will need to run:
install.packages('webshot')
webshot::install_phantomjs()
Once webshot is installed, it should work automatically:
---
title: "Change chart size chart on pdf file using plotly"
output:
pdf_document: default
papersize: a4
---
```{r include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(plotly)
```
```{r, out.width="100%"}
plot_ly(x = cars[1:10,]$speed,y = cars[1:10,]$dist, width = 1000, height = 1200)
```
Will update this answer if I can work out exactly why it works, but hope that helps!
You need to be very careful while working with plotly graphs with r markdown pdf.
While creating the plotly graph,
Don't forget to explicitly set the size (width and height) of the graph
Use the chunk option of out.width and out.height. They both accept pt,mm,in,px,%
If you're producing the latex output in the pdf then 'px' will not work.
Please find the below code for the graph and the output of the same.
f <- list(
size = 30,
family = 'sans-serif'
)
m <- list(
l = 100,
r = 50,
b = 0,
t = 0,
pad = 4
)
p <- plot_ly(width = 800, height = 800) %>%
add_markers(data = pressure, x = pressure$temperature, y = pressure$pressure) %>%
layout(font = f, margin = m)
p
The output produced by this is
with size and margins
Now after modifying the code chunk options as below:
```{r pressure2, echo=FALSE, out.height="150%", out.width="150%"}
f <- list(
size = 30,
family = 'sans-serif'
)
m <- list(
l = 100,
r = 50,
b = 0,
t = 0,
pad = 4
)
p <- plot_ly(width = 800, height = 800) %>%
add_markers(data = pressure, x = pressure$temperature, y = pressure$pressure) %>%
layout(font = f, margin = m)
p
```
you will get a much bigger graph
Keep coding!
Have you tried only using fig.height & fig.width options and remove out.width and out.height?
{r , fig.height=6, fig.width=9.5}
I am playing around with plotly and I've had success using HTML notebooks using this. It's a little more trial and error but you don't have to rebuild the plots.
I have an rmarkdownfile with a chunck that has a loop that creates many pages. Below is a toy example. See the "loop_chunk" code chunk. The "loop_chunk" has fig.width=9, fig.height=6, results="asis" and I am running into a problem where i need to reduce the size of a plot inside loop_chunk. All plots are 9x6 but I need to adjust one plot. I found the codee below: http://michaeljw.com/blog/post/subchunkify/
and I tried using it below but when you run the code you can see that there are 2 plots on pages 3 and 5 and there should not be. it is somehow not keeping the \newpages. There should be 1 plot on pages 2,3,4 and 5. There should only be 5 pages.
Any idea how to fix this?
---
title: "Untitled"
output: pdf_document
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE , comment = NA, message= FALSE, warning = TRUE)
subchunkify <- function(g, fig_height=7, fig_width=5) {
g_deparsed <- paste0(deparse(
function() {g}
), collapse = '')
sub_chunk <- paste0("
`","``{r sub_chunk_", floor(runif(1) * 10000), ", fig.height=", fig_height, ", fig.width=", fig_width, ", echo=FALSE}",
"\n(",
g_deparsed
, ")()",
"\n`","``
")
cat(knitr::knit(text = knitr::knit_expand(text = sub_chunk), quiet = TRUE))
}
data = data.frame(group= c("A","A"), value = c(1,3))
```
```{r loop_chunk, fig.width=9, fig.height=6, results="asis", message= FALSE, warning = FALSE}
for(i in 1:nrow(data)){
cat(paste0("\\newpage\n # Page ", i ," \n"))
plot(data$value[i])
cat("\n\n")
cat(paste0("\\newpage\n ## page with smaller plot \n\n"))
cat("Here is some text on this page for the smaller plot.")
cat("\n\n")
data2 = data.frame(x = 7, y = 900)
library(ggplot2)
myplot = ggplot(data2, aes(x = x, y = y ))+geom_point()
subchunkify(myplot , 4,4 )
# print(myplot) -> IS there a way to just reduce the height and width with print()?
cat("\n\n")
}
```
Using your subchunkify() function for the graphics::plot call outputs those plots to the intended pages. Replacing plot(data$value[i]) in your second chunk with
subchunkify(plot(data$value[i]), 5, 5)
outputs the 5 pages with plots as intended (where height & width are set to 5/can be edited to conditionally set dimensions for a specific plot).
I want to display two charts with the rCharts package, one next to the other, more or less like the two pies are displayed in this link:
http://nvd3.org/examples/pie.html
I have a partial solution using <iframe>, but the solution has three problems:
It is too case specific
Including controls becomes a complicated task
It does not look too nice
Minimum working example:
---
title: "Example"
output: html_document
---
```{r rcht, message=FALSE, echo=FALSE, results='asis'}
library(rCharts)
df<-data.frame(label=c("One","Two","Three"),valuea=c(1,2,3),othera=c(10,11,12),
valueb=c(4,5,6),otherb=c(10,11,12),stringsAsFactors = FALSE)
p1 <- nPlot(valuea~ label, data = df, type = 'pieChart',height = 225, width = 300)
p2<- nPlot(valueb~ label, data = df, type = 'pieChart',height = 225, width = 300)
p1$show('inline', include_assets = TRUE, cdn = F)
p2$show('inline', include_assets = TRUE, cdn = F)
```
```{r message=FALSE, echo=FALSE}
p1$save("pie1.html", standalone = TRUE)
p2$save("pie2.html", standalone = TRUE)
```
<div align="center">
<font size="10" color="black" face="sans-serif">Both Pies</font><br>
<p>
<iframe src="pie1.html" height="400" width="400"></iframe>
<iframe src="pie2.html" height="400" width="400"></iframe>
</p>
<div>
I know pie charts should not be used and that I could use a multi-bar chart. However, I want to use this type of layout with other kinds of charts in the rCharts package.
Additionally, I would like to include controls in the charts whilst they are shown next to each other. Including the following code before the $save() function adds the controls:
```{r message=FALSE, echo=FALSE}
p1$addControls('y','valuea',values=c('valuea','othera'))
p2$addControls('y','valueb',values=c('valueb','otherb'))
```
This issue is less relevant to me, but if someone has a solution (preferably with only one control for both charts), it would be great.
I understand all this might be too much to handle from R. Any help/advice is appreciated.
Not elegant, but functional (I did not try it with controls):
---
title: "Example"
output: html_document
---
```{r rcht, message=FALSE, echo=FALSE, results='asis'}
library(rCharts)
library(htmltools)
df <- data.frame(label=c("One","Two","Three"),valuea=c(1,2,3),othera=c(10,11,12),
valueb=c(4,5,6),otherb=c(10,11,12),stringsAsFactors = FALSE)
p1 <- nPlot(valuea~ label, data = df, type = 'pieChart',height = 225, width = 300)
p2 <- nPlot(valueb~ label, data = df, type = 'pieChart',height = 225, width = 300)
```
```{r echo=FALSE, results="asis"}
cat("<table width='100%'><tr style='width:100%'><td width='50%'>")
```
```{r echo=FALSE, results="asis"}
p1$show('inline', include_assets = TRUE, cdn = FALSE)
```
```{r echo=FALSE, results="asis"}
cat("</td><td>")
```
```{r echo=FALSE, results="asis"}
p2$show('inline', include_assets = TRUE, cdn = FALSE)
```
```{r echo=FALSE, results="asis"}
cat("</td></tr></table>")
```
Hi I am having the same problem with controls it looks that in the viewer of R-studio everything works fine but not when I compile with Rmarkdown it doesn't show the plot at all.
```{r results = 'asis', comment = NA}
require(rCharts)
require(datasets)
p2 <- nPlot(mpg ~ cyl, group = 'wt',
data = mtcars, type = 'scatterChart')
p2$xAxis(axisLabel = 'Log2')
p2$yAxis(axisLabel = 'Log2')
p2$chart(tooltipContent = "#! function(key, x, y, e){
return '<b>Name:</b> ' + e.point.GeneID
} !#")
p2$chart(color = c('red', 'green'))
p2$addControls("x", value = 'mpg', values = names(mtcars))
p2$addControls("y", value = 'cyl', values = names(mtcars))
cat('<style>.nvd3{height: 400px;}</style>')
p2$print('chart2', include_assets = TRUE)
```
The code above is the addControls are removed actually works also in the rmarkdown.
Also, if you try to run the code above in Rstudio console (just from p2<-nPlot to cat command) and then calling p2 I can actually see the controls.