How to plot a decision tree horizontally in R Markdown? - r

In R Markdown, I would like to plot a decision tree horizontally, so that it fits better the entire PDF page. This code plots it vertically:
```{r, message=FALSE, warning = FALSE, echo=FALSE, cache = FALSE}
rpart.lrn <- makeLearner("classif.rpart", predict.type = "prob", fix.factors.prediction = FALSE)
model = train(rpart.lrn, task = classif.task, subset = train.set)
tree <- getLearnerModel(model)
rpart.plot(tree) # visualise the tree
```
How can I plot it horizontally instead?

Have you tried so set fig.height and fig.width, for example {r ggpair, echo=FALSE, message = FALSE, warning = FALSE, fig.height = 12, fig.width = 12}

Related

How to suppress downloading progress in HTML file

I am using imfr package to download some IMF data series
library(imfr)
t <- imf_data(database_id = "BOP", indicator = "BCA_BP6_USD",
country = "all", start = "1990", freq = "Q")
I prespecified certain parameters in a separate chunk before to suppress downloading progress
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, error = FALSE, results = 'hide', fig.keep = 'all')
However, neither of these options did the job. Moreover results = 'hide' suppressed all the output including text and figures.
How can I solve this issue without having a separate chunk for data downloading?
You can capture all those downloads message and progress bar in capture.output and wrap it with invisible. (Got this idea from this question and answer on SO).
And then make a wrapper function imf_data which works the same (mask the imfr::imf_data function) but does not print all those download messages and the progress bar.
---
title: "IMF Data"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
imf_data <- function(...) {
invisible(capture.output(dt <- imfr::imf_data(...)))
return(dt)
}
```
```{r}
library(imfr)
t <- imf_data(database_id = "BOP", indicator = "BCA_BP6_USD",
country = "all", start = "1990", freq = "Q")
```
```{r, comment=""}
head(t)
```

dfSummary() graphs are not printed in the HTML file

When using dfSummary() from the "summarytools" package in Rmarkdown -file, I get Graph -part of the summary printed as plain ASCII despite the st_options(plain.ascii = FALSE). The correct graphs are printed in the /tmp -folder, but are not displayed in the html-file.
{r Summary, results='asis', echo=FALSE}
st_options(bootstrap.css = FALSE,
plain.ascii = FALSE,
style = "rmarkdown",
dfSummary.silent = TRUE)
st_css()
dfSummary(df_data, tmp.img.dir = "/tmp", valid.col = FALSE, graph.magnif = 0.75)
Summary from the code above gets printed like this:
How can I get the proper graphs (which are in the tmp-folder nice and shiny) included in the HTML file?
How can I get the proper graphs (which are in the tmp-folder nice and shiny) included in the html file?
According to the Dominic's vignette - "Recommendations for Using summarytools With Rmarkdown":
For dfSummary(), grid is recommended.
So, you may try following, using print() function:
```{r Summary, results = "asis", cache = FALSE}
base::print(summarytools::dfSummary(df_data,
valid.col = FALSE, # drop Valid column if redundant
style = "grid", # set style to “grid”
plain.ascii = FALSE,
graph.magnif = 0.75, # zoom factor (max = 1) for bar plots and histograms
tmp.img.dir = "./tmp"),
dfSummary.silent = TRUE, # Suppresses messages about temporary files
bootstrap.css = FALSE)
```
Or, if you prefer to declare st_options() first:
```{r Summary2, results = 'asis', echo = FALSE}
st_options(bootstrap.css = FALSE,
dfSummary.silent = TRUE)
st_css()
dfSummary(df_data,
valid.col = FALSE,
style = "grid",
plain.ascii = FALSE,
graph.magnif = 0.75,
tmp.img.dir = "./tmp")
```
Let us know if this is helpful.
Just add style="grid":
dfSummary(df_data, style = "grid", tmp.img.dir = "/tmp",
valid.col = FALSE, graph.magnif = 0.75)
The documentation is not clear enough on this point, it'll be fixed in the next version.

Change output width of plotly chart size in R Markdown PDF output

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.

Display two rCharts NVD3 figures next to each other in rmarkdown

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.

Setting rChart width and height

In the (few so far) learning-oriented examples on the web of integrating knitr and rCharts we often see a line of code within an R chunk as follows:
options(RCHART_WIDTH = 800, RCHART_HEIGHT = 500)
When I include this sort of variable setting in an R chunk of an R markdown document it seems to make no difference at all to the actual size of the eventual chart in html. What extra thing am I missing that will let me control the width and height of rCharts? Reproducible *.rmd file is below.
```{r echo = F, message = F, cache = F}
opts_chunk$set(results = 'asis', comment = NA, message = F, tidy = F, echo=FALSE, cache=FALSE)
require(rCharts)
options(RCHART_WIDTH = 600, RCHART_HEIGHT = 400)
```
## Example plot with un-customised dimensions
```{r}
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE, cdn=TRUE)
```
The issue is that the print method does not include the css that sizes the charts. Easiest fix would be to add the following css to your Rmd file .rChart{width: 600px; height: 400px}. The print method is being rewritten and we are trying to figure out the most flexible yet useful way to do it.

Resources