Setting rChart width and height - r

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.

Related

Adding image to flextable to be generated with knitr fails but works in RMarkdown chunk

Running R4.1.2 and Windows 10:
I'm trying to knit a document that has a flextable with a ggplot image that was created via ggsave. When I run the code chunk in RMarkdown, it works fine, but when I attempt to knit a word document, I get the following error. If I don't include the image, knitr works fine.
Quitting from lines 350-376 (RPOPS_Draft_Test2.0.Rmd)
Error in read_xml.raw(charToRaw(enc2utf8(x)), "UTF-8", ..., as_html = as_html, :
xmlParseEntityRef: no name [68]
Calls: <Anonymous> ... as_xml_document -> as_xml_document.character -> read_xml.raw
Execution halted
Below are the yaml headers. I am using officedown, as I know this package is required to have images in flextables be rendered in Word.
---
title: "something: `r params$program`"
output:
officedown::rdocx_document:
reference_docx: P:/Reference_doc
params:
program: "something"
---
And here is the code chunk causing the issue.
```{r overall1_flextable}
# chart creation
plot_overall1 <- f_overall_cht(overall_chart1)
plot_overall1_img_out <- ggsave(filename = "plotoverall1img.png", plot = plot_overall1, width = 3.05, height = 0.37, dpi = 600, device = "png")
plot_overall1_in <- file.path(getwd(), "plotoverall1img.png")
example_tibble <- tibble(
col_name = "chart to the right",
chart = ""
)
ft <- flextable(example_tibble)
ft <- compose(ft, i=1, j=2,
value = as_paragraph(
as_image(src = plot_overall1_in, width = 3.05, height = 0.37),
as_chunk(chart)),
part = "body"
)
autofit(ft)
```
I haven't been able to find much on this issue, so any help would be appreciated.
I could not reproduce your error. Below the code to produce your table. There are two solutions, my recommended solution (documented here: https://ardata-fr.github.io/flextable-book/cell-content-1.html#base-plots-and-ggplot-objects) and something closer to what you wrote.
---
title: "test"
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
library(officedown)
library(officer)
library(flextable)
library(ggplot2)
library(tibble)
# chart creation
plot_overall1 <- ggplot(iris, aes(Sepal.Length, Petal.Length)) +
geom_point()+
theme_void()
```
## Recommanded
The solution below is corresponding to the recommanded way.
```{r}
example_tibble <- tibble(
col_name = "chart to the right",
chart = list(plot_overall1)
)
ft <- flextable(example_tibble)
ft <- compose(ft,
j = "chart",
value = as_paragraph(
gg_chunk(value = chart, width = 3.05, height = 0.37, unit = "in")
),
part = "body"
)
autofit(ft)
```
## From scratch
The solution below is corresponding to the way you tried.
```{r}
png_file <- tempfile(fileext = ".png")
plot_overall1_img_out <- ggsave(
filename = png_file,
plot = plot_overall1,
width = 3.05, height = 0.37,
dpi = 600, device = "png")
example_tibble <- tibble(
col_name = "chart to the right"
)
ft <- flextable(example_tibble,
col_keys = c("col_name", "chart"))
ft <- compose(ft,
i = 1, j = "chart",
value = as_paragraph(
as_image(src = png_file, width = 3.05, height = 0.37, unit = "in")
),
part = "body"
)
autofit(ft)
```

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.

After upgrading: rCharts not working in rmarkdown

after I upgraded to rCharts version 0.4.5 I am not able to see a plot in my rmarkdown file anymore. I have produced a minimum example rmd where I cannot see the plots anymore (if I open the output in my browser). I have absolutely no clue which package is responsible for this. Note that it works fine if I use the $save mode and just import the created html file as in example number 2.
Do you have any idea?
I created a minimum example from a highcharts demo. This thread also helped me.
```{r echo = F, message = F, cache = F}
# Set options for plots.
library(knitr)
opts_chunk$set(results = 'asis', comment = NA, message = F, tidy = F, echo=FALSE, cache=FALSE)
```
```{r, echo=FALSE}
library(rCharts)
a <- hPlot(Pulse ~ Height, data = MASS::survey, type = "bubble", title = "Zoom demo", subtitle = "bubble chart", size = "Age", group = "Exer")
a$chart(zoomType = "x")
a$exporting(enabled = T)
a$show('iframesrc', cdn = TRUE)
```
```{r, echo=FALSE}
library(rCharts)
a <- hPlot(Pulse ~ Height, data = MASS::survey, type = "bubble", title = "Zoom demo", subtitle = "bubble chart 2", size = "Age", group = "Exer")
a$chart(zoomType = "x")
a$exporting(enabled = T)
a$save('plot2.html', standalone = TRUE)
```
<iframe src="plot2.html" height="450" width="850" frameBorder="0"></iframe>
The answer is a new "feature", that transforms links of e.g. sources starting with http://www. as //www. to make it also work with https://. On webservers, this is interpreted correctly but if you open a local html file, //www. will not be recognized. The issue is reported on the github page.

embed rChart in Markdown

I am trying to embed a NVD3 chart in a Markdown document. I am on a Ubuntu64 system with RStudio 0.98.932, R 3.1.0, rCharts 0.4.2, the browser is Chrome.
The instructions/code from this link:
```{r}
library(rCharts)
library(knitr)
opts_chunk$set(comment = NA, results = "asis", comment = NA, tidy = F)
hair_eye_male = subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = 'Eye',
data = hair_eye_male, type = 'multiBarChart'
)
n1$set(width = 600)
# n1$show('iframesrc', cdn = TRUE) # option 1
# n1$show('inline', include_assets = TRUE, cdn = TRUE) # option 2
```
Neither of the options [n1$show] work, I just get code in a browser. Is there another way of including NVD3 documents in Markdown?
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
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)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Source:Knitr HTML in R Markdown
This code is working for me. I am using ubuntu64 and same config you mentioned.
```{r, echo=FALSE,results='asis',comment=NA}
library(rCharts)
hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = "Eye", data = hair_eye_male, type = "multiBarChart")
n1$show('iframesrc',cdn=TRUE)
```
Note : you must write results='asis' and comment = NA in chunk options and not use opts_chunk$set as you have in your code block and what you pasted to copy.com.

Resources