Question: How to place xtable object to the left side of page or how to disable centering globally.
I'm struggling to figure out how to place xtable object on the left side. I have got a *.Rmd file and all this goes to the relevant r chunk.
require(xtable)
df <- data.frame(x=seq(1,10,1),y=rnorm(10))
Xtab <- xtable(df, digits=0, caption="\\textbf{MINIMAL/IDEAL}",
floating=FALSE, latex.environments = c("left"))
print(Xtab, size = "small", include.colnames=FALSE)
I have included the following after reading various sources (print.xtable; xtable manual etc.)
1) floating=FALSE
2) latex.environments = c("left")
I have searched SO and used some of the hints but all failed.
It seems to make quite a difference whether you pass a parameter to xtable() or to print(xtable()). The following chunk creates a table according to your data that is aligned at the left of the page in the pdf file.
```{r, results='asis',echo=FALSE}
library(xtable)
df <- data.frame(x=seq(1, 10, 1),y = rnorm(10))
print(xtable(df,digits=0, caption="\\textbf{MINIMAL/IDEAL}"), include.colnames=FALSE, size = "small", comment=FALSE, latex.environments="flushleft")
```
However, as you can see, the caption remains at the center of the page.
Related
I'm failing to get left aligned numbers in kableExtra in combination with formattable's barplots in table cells.
Code to reproduce in rmarkdown format:
title: "Untitled"
output: html_document
knitr::opts_chunk$set(echo = TRUE)
library("formattable")
library("kableExtra")
Example
summary(cars)
cars$speed <- cars$speed * 100
Get a nice table
The table's first column is filled with tiny bar plots.
All code is written following http://haozhu233.github.io/kableExtra/awesome_table_in_html.html manual of kableExtra.
plot.table <- cars
# need to modify the first few values to make sure the effect is visible.
plot.table$speed[1] <- 3
plot.table$speed[2] <- 25
plot.table$speed[3] <- 100
plot.table$speed <- color_bar("lightgreen")(plot.table$speed)
kbl(x = plot.table,
escape = F) %>%
kable_styling(bootstrap_options = c("striped", "hover"), fixed_thead = T)
The first three rows show values that are small in comparison to the rest of the values in the table.
This makes theirs bars short and results in weirdly aligned numbers. The alignment is done according to the rightmost end of the green bar.
Inspecting the respective html element (e.g. FireFox "Inspect Element") reveals that the element "direction" is "rtl", which seems to be the default in kableExtra.
Manually modifying the value of this parameter to "ltr" yields nicely left aligned values extending across the bar's end.
Unfortunately, I couldn't find the parameter in color_bar to modify this behaviour.
Any help pointing me to a way to get the values left aligned would be highly appreciated.
as #juljo mentioned one obviously needs to modify the respective function. The body of the function could be copied out of the package contents.
f.color_bar <- function (color = "lightgray", fun = "proportion", ...)
{
fun <- match.fun(fun)
formattable::formatter("span", style = function(x) style(display = "inline-block",
direction = "ltr", `border-radius` = "4px",
`padding-right` = "2px", `background-color` = csscolor(color),
width = percent(fun(as.numeric(x), ...))))
}
This hard coded the left to right behaviour, but isn't variable here as well.
My visNetwork is not displayed at all when the displaying is attempted in a for loop. In a regular R script, I use the print function and it works just fine, but it does not work in an R Markdown document.
Here is a (hopefully) reproducible example:
---
title: "I want my beautiful networks back!"
---
# First example that works
```{r}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
vn <- visNetwork(nodes, edges, width = "100%")
vn # Or print(vn)
```
# When does it not work?
## In a for loop
```{r}
for (i in 1) vn
```
## In a for loop + using print
This will display the network in the Viewer.
```{r}
for (i in 1) print(vn)
```
## And also in functions
Same remark...
```{r}
foo <- function(x) print(x)
foo(vn)
```
I'm using Rstudio version Version 1.1.383 and
here is the result of a sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6
other attached packages:
[1] visNetwork_2.0.2
I just found a little workaround, consisting the following steps:
Save plot as HTML
Include the HTML code in RMD file
Here an example:
```{r}
for (i in 1:3){
visSave(vn, file = paste0("test",i,".html"))
}
```
```{r, results='asis'}
for (i in 1:3){
cat(htmltools::includeHTML(paste0("test",i,".html")))
}
```
Another solution is to use print(htmltools::tagList())
This prevents the !DOCTOOLS showing in the output.
```{r}
for (i in 1) print(htmltools::tagList(vn))
```
I came across the same issue / solution when working with Datatables and the solution was provided here by #Yihui: https://github.com/rstudio/DT/issues/67
Edit I've since realised that you need at least one visnetwork plotted outside of the loop, i.e. outside of print(htmltools::taglist()), otherwise the script to render is not added to the html file.
You can remove the !DOCTYPE by operating on the string.
cat (as.character(htmltools::includeHTML(paste0("vn",".html"))) %>%
{gsub("<!DOCTYPE html>","",.,fixed = TRUE)} %>%
{sub("\n","",.)}
)
I had the same problem but also wanted to knit my Rmd from the command line, not within RStudio, to easily generate reports for many different parameters, e.g.:
Rscript -e "rmarkdown::render('graphical-res-vis-reports.Rmd', \
params = list(tissue = '${tissue}'), \
output_file = sprintf('graphical-analysis-results_%s.html','${tissue}'))"
The htmltools::includeHTML(html_path) trick worked well when knitting from within RStudio, but it spat out a pandoc error when I tried to knit it from the command line because it's effectively concatenating multiple standalone HTMLs, which does not result in a valid HTML format. (EDIT: the pandoc error may have also been because R from the command line was using a much older version of pandoc than RStudio, but using iframes is still much cleaner.)
I finally found a solution using iframes that works well. Here is a minimal reproducible example:
---
title: "Finally, a way to print visNetworks in a loop!"
---
```{r make networks}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
html_list <- c()
for (i in 1:3){
vn <- visNetwork(nodes, edges)
outfile <- sprintf("vn_%s.html", i)
visSave(vn, file=outfile)
html_list <- c(html_list, outfile)
}
```
```{r plot networks, results="asis"}
for (i in html_list){
print(htmltools::tags$iframe(title = "My embedded document",
src = f, height = "650", width = "900", frameBorder = "0"))
}
```
EDIT: Note that changing the iframe height and width doesn't resize the object from the HTML file. However, you can increase the size of the visNetwork HTML object with a simple text replacement. In this example, I remove the whitespace padding and change the size from 960x500 to 960x960:
visSave(v1, file = out_html)
# adjust browser window size
cmd = sprintf('sed -i \'s|"browser":{"width":960,"height":500,"padding":40,"fill":false}|"browser":{"width":960,"height":960,"padding":0,"fill":false}|\' %s', out_html)
system(cmd)
I'm having difficulty in getting pander tables to render in a slidify document (specifically with a call to pander.lm).
For example, the below works
```{r panderWorks, results = "asis"}
id <- rep(1:3, each = 2)
condition <- rep(c("A", "B"), 3)
score <- rnorm(6, 10, 3)
d <- data.frame(id, condition, score)
library(pander)
pander(d, style = "rmarkdown")
```
while the following does not
```{r panderFails, results = "asis"}
data(iris)
pander(lm(Sepal.Width ~ Species, data = iris),
style = "rmarkdown")
```
Note that I actually can get the first chunk to render correctly without the results = "asis" option, but that's worked for me in the past. I've tried changing many options and still no luck. It's also worth noting that I have no problem getting this to render in a standard rmarkdown document. It's only within slidify that I have issues.
I'm working within the io2012 framework, with the highlight.js highlighter and the zenburn highlight theme. I've loaded the mathjax widget and the mode is selfcontained.
Below I've attached my output from sessionInfo().
Any ideas?
is there a simple way (e.g., via a chunk option) to get a chunk's source code and the plot it produces side by side, as on page 8 (among others) of this document?
I tried using out.width="0.5\\textwidth", fig.align='right', which makes the plot correctly occupy only half the page and be aligned to the right, but the source code is displayed on top of it, which is the normal behaviour.
I would like to have it on the left side of the plot.
Thanks
Sample code:
<<someplot, out.width="0.5\\textwidth", fig.align='right'>>=
plot(1:10)
#
Well, this ended up being trickier than I'd expected.
On the LaTeX side, the adjustbox package gives you great control over alignment of side-by-side boxes, as nicely demonstrated in this excellent answer over on tex.stackexchange.com. So my general strategy was to wrap the formatted, tidied, colorized output of the indicated R chunk with LaTeX code that: (1) places it inside of an adjustbox environment; and (2) includes the chunk's graphical output in another adjustbox environment just to its right. To accomplish that, I needed to replace knitr's default chunk output hook with a customized one, defined in section (2) of the document's <<setup>>= chunk.
Section (1) of <<setup>>= defines a chunk hook that can be used to temporarily set any of R's global options (and in particular here, options("width")) on a per-chunk basis. See here for a question and answer that treat just that one piece of this setup.
Finally, Section (3) defines a knitr "template", a bundle of several options that need to be set each time a side-by-side code-block and figure are to be produced. Once defined, it allows the user to trigger all of the required actions by simply typing opts.label="codefig" in a chunk's header.
\documentclass{article}
\usepackage{adjustbox} %% to align tops of minipages
\usepackage[margin=1in]{geometry} %% a bit more text per line
\begin{document}
<<setup, include=FALSE, cache=FALSE>>=
## These two settings control text width in codefig vs. usual code blocks
partWidth <- 45
fullWidth <- 80
options(width = fullWidth)
## (1) CHUNK HOOK FUNCTION
## First, to set R's textual output width on a per-chunk basis, we
## need to define a hook function which temporarily resets global R's
## option() settings, just for the current chunk
knit_hooks$set(r.opts=local({
ropts <- NA
function(before, options, envir) {
if (before) {
ropts <<- options(options$r.opts)
} else {
options(ropts)
}
}
}))
## (2) OUTPUT HOOK FUNCTION
## Define a custom output hook function. This function processes _all_
## evaluated chunks, but will return the same output as the usual one,
## UNLESS a 'codefig' argument appeared in the chunk's header. In that
## case, wrap the usual textual output in LaTeX code placing it in a
## narrower adjustbox environment and setting the graphics that it
## produced in another box beside it.
defaultChunkHook <- environment(knit_hooks[["get"]])$defaults$chunk
codefigChunkHook <- function (x, options) {
main <- defaultChunkHook(x, options)
before <-
"\\vspace{1em}\n
\\adjustbox{valign=t}{\n
\\begin{minipage}{.59\\linewidth}\n"
after <-
paste("\\end{minipage}}
\\hfill
\\adjustbox{valign=t}{",
paste0("\\includegraphics[width=.4\\linewidth]{figure/",
options[["label"]], "-1.pdf}}"), sep="\n")
## Was a codefig option supplied in chunk header?
## If so, wrap code block and graphical output with needed LaTeX code.
if (!is.null(options$codefig)) {
return(sprintf("%s %s %s", before, main, after))
} else {
return(main)
}
}
knit_hooks[["set"]](chunk = codefigChunkHook)
## (3) TEMPLATE
## codefig=TRUE is just one of several options needed for the
## side-by-side code block and a figure to come out right. Rather
## than typing out each of them in every single chunk header, we
## define a _template_ which bundles them all together. Then we can
## set all of those options simply by typing opts.label="codefig".
opts_template[["set"]](
codefig = list(codefig=TRUE, fig.show = "hide",
r.opts = list(width=partWidth),
tidy = TRUE,
tidy.opts = list(width.cutoff = partWidth)))
#
A chunk without \texttt{opts.label="codefig"} set...
<<A>>=
1:60
#
\texttt{opts.label="codefig"} \emph{is} set for this one
<<B, opts.label="codefig", fig.width=8, cache=FALSE>>=
library(raster)
library(RColorBrewer)
## Create a factor raster with a nice RAT (Rast. Attr. Table)
r <- raster(matrix(sample(1:10, 100, replace=TRUE), ncol=10, nrow=10))
r <- as.factor(r)
rat <- levels(r)[[1]]
rat[["landcover"]] <- as.character(1:10)
levels(r) <- rat
## To get a nice grid...
p <- as(r, "SpatialPolygonsDataFrame")
## Plot it
plot(r, col = brewer.pal("Set3", n=10),
legend = FALSE, axes = FALSE, box = FALSE)
plot(p, add = TRUE)
text(p, label = getValues(r))
#
\texttt{opts.label="codefig"} not set, and all settings back to ``normal''.
<<C>>=
lm(mpg ~ cyl + disp + hp + wt + gear, data=mtcars)
#
\end{document}
I see 3 possibilities
for beamer presentations, I'd go for \begin{columns} ... \end{columns} as well.
If it is only one such plot: Minipages
Here I used a table (column code and column result). (This example is "normal" Sweave)
For all three, the chunk options would have include = FALSE, and the plot would "manually" be put to the right place by \includegraphics[]{}.
You can display the text in a 'textplot' from package PerformanceAnalytics or gplots.
(Little) downside: To my knowledge there is no Syntax highlighting possible.
Sample Code:
```{r fig.width=8, fig.height=5, fig.keep = 'last', echo=FALSE}
suppressMessages(library(PerformanceAnalytics))
layout(t(1:2))
textplot('plot(1:10)')
plot(1:10)
```
I have a number of tables with text around them describing them. Something like this:
This table shows blah blah...
<<echo=FALSE, results=tex>>=
print(
xtable(x,
caption = "blah", label = "tab:four", table.placement = "tbp", caption.placement = "top")
, size = "small", table.placement="ht")
#
This table shows blah blah...
<<echo=FALSE, results=tex>>=
print(
xtable(x,
caption = "blah", label = "tab:five", table.placement = "tbp", caption.placement = "top")
, size = "small", table.placement="ht")
#
I want all my descriptive text to be in line with the tables so that they follow in the sequence that I am writing them. But around the end of a page, some tables move off onto the next page and the descriptive text is just free floating. Is there some particular table.placement command that will ensure that everything stays the way that it is written?
The latex float package provides the float specifier H, which allows you to force tables and figures to be precisely in the location they occur in the latex code. For example:
\usepackage{float}
...
<<echo=FALSE, results=tex>>=
print(xtable(x),table.placement="H")
#
See here for the table placement. You could try "!h" to force the table to stay where you wan't.
I find \clearpage after a float is sometimes useful.