Here's my code that's supposed to display to graphics next to each other, but fails to do so. In fact the sweave part is not interpreted.
\begin{figure}[h]
\begin{center}
\begin{minipage}[t]{.485\linewidth} %
<<fig=true,echo=false>>=
print(graph2)
#
\newline{\color{red}{\caption{\label{idx}Graph one}}}
\end{minipage}
\hspace{.02\linewidth}
\begin{minipage}[t]{.485\linewidth}%
<<fig=true,echo=false>>=
print(graph2)
#
\newline{\color{red}{ \caption{\label{pb}Graph two}}}
\end{minipage}
\end{center}
\end{figure}
graph1,graph2 is just any given graph created by qplot. Both graphs work just fine outside a minipage. I know this topic has been around, but somehow I could not get solutions to got that worked for others like this one.
Plus I have a little side question: What's the argument to prevent Sweave from generating both .eps and .pdf ? The manual just states that it is the default. However I am sure that I just use pdflatex and hence do not need .eps.
Eh, this is actually cheating, but a found a nice workaround on John's blog. It's not using minipage but it's getting it done by using subfigure. Subfigure did not have any problems with Sweave. Nice!
If you are interested in this solution check this site. Still i´d like to know how to do it with minipage :)
Replacing \hspace with \hfill does the trick. The plots are from the ggplot documentation. minipage also works nicely for putting two xtable side by side, or a table and a plot.
\documentclass{article}
\usepackage{color}
\begin{document}
\begin{figure}[h]
\begin{center}
\begin{minipage}[t]{.49\linewidth} %
<<fig=true,echo=false>>=
require(ggplot2)
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
library(plyr)
ds <- ddply(df, .(gp), summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(x = gp, y = y)) +
geom_point() +
geom_point(data = ds, aes(y = mean),colour = 'red', size = 3)
#
\newline{\color{red}{\caption{\label{idx}Graph one}}}
\end{minipage}
\hfill
\begin{minipage}[t]{.49\linewidth}
<<fig=true,echo=false>>=
ggplot() +
geom_point(data = df, aes(x = gp, y = y)) +
geom_point(data = ds, aes(x = gp, y = mean),
colour = 'red', size = 3) +
geom_errorbar(data = ds, aes(x = gp, y = mean,
ymin = mean - sd, ymax = mean + sd),
colour = 'red', width = 0.4)
#
\newline{\color{red}{ \caption{\label{pb}Graph two}}}
\end{minipage}
\end{center}
\end{figure}
\end{document}
Related
I have two ggplot graphs. When plot individually in Markdown, they have the right aspect ratio. When plot them side by side with plot_grid(), they look vertically stretched.
I just need show them side by side, but keep aspect ratio (or, at least, reduce height)
I'm not sure if I must change it using markdown parameters, change something in plot_grid() or the plot area, or in the graphs themselves.
Thanks! :)
NOTE: Data is really irrelevant for this case. If needed, I add my code :)
values1.graph <-ggplot(data = values1.df) +
geom_histogram(mapping = aes(x = values1, y = after_stat(density)), fill="steelblue", colour="black", binwidth = 1) +
ggtitle("Hist .vs. Norm 1") +
stat_function(fun = dnorm, args = with(values1.df, c(mean = mean(values1), sd = sd(values1))))
values2.graph<-ggplot(data = values2.df) +
geom_histogram(mapping = aes(x = values2, y = after_stat(density)), fill="steelblue", colour="black", binwidth = 1) +
ggtitle("Hist .vs. Norm 2") +
stat_function(fun = dnorm, args = with(values2.df, c(mean = mean(values2), sd = sd(values2))))
plot_grid(values1.graph, values2.graph, labels = NULL)
The resulting graph is:
But, what I want are the graphs with the original aspect ratio, as it shows when I plot them individually:
I know the graphs will be smaller when keeping the aspect ratio, but i don't mind it. What I don't want is to show a leptokurtic distribution when it is not.
Finally, what I found is that you can SET the size in Markdown with fig.width and fig.height, or out.width and out.height
{r Graphs, echo=FALSE, fig.width=14, fig.height=5}
I've written some simple code to plot some data, but for some reason I can't get it to print out on the html document when I knit it?
library(datasets)
library(ggplot2)
ggplot(ChickWeight, aes(x = Time, y = weight)) + geom_point()
I expect to see an image in the output, but instead, I just see the html code for one...
'''r
library(datasets)
library(ggplot2)
ggplot(ChickWeight, aes(x = Time, y = weight)) + geom_point()
'''
<img src="hw5_files/figure-html/unnamed-chunk-3-1.png" width="672" />
Is there any reason why this would be happening? I'm using Ubuntu 18.04 and R 3.4.4
Edit:
My entire markdown file for this looks like this:
---
title: DS Homework
author: Aaron
date: 4/10/2020
output: html_document
---
1. Question 1:
a. Some part a
b. Some part b
'''{r}
library(datasets)
library(ggplot2)
ggplot(ChickWeight, aes(x = Time, y = weight)) + geom_point()
'''
2. Question 2:
ggplot works well in "interactive" mode however when you are sourcing your code you need to explicitly call print(). Thus either
library(datasets)
library(ggplot2)
print(ggplot(ChickWeight, aes(x = Time, y = weight)) + geom_point())
or
library(datasets)
library(ggplot2)
p <- ggplot(ChickWeight, aes(x = Time, y = weight)) + geom_point()
print(p)
Should work
Hope it helps
I've since figured out that in fact, it was actually, because I was indenting the code blocks, unindenting the code blocks fixed the issue
1. Question 1:
a. Some part a
b. Some part b
'''{r}
library(datasets)
library(ggplot2)
ggplot(ChickWeight, aes(x = Time, y = weight)) + geom_point()
'''
2. Question 2:
to
1. Question 1:
a. Some part a
b. Some part b
'''{r}
library(datasets)
library(ggplot2)
ggplot(ChickWeight, aes(x = Time, y = weight)) + geom_point()
'''
2. Question 2:
put print() before the ggplot or any other plotting line
e.g
from
surface3d(wt1, hp1,pred, alpha=.2)
to
print(surface3d(wt1, hp1,pred, alpha=.2))
Alternatively you can these in the code chunk if you are using rgl library
options(rgl.useNULL = TRUE)
setupKnitr(autoprint=TRUE)
E.g.
\\```{r}
library(rgl)
options(rgl.useNULL = TRUE)
setupKnitr(autoprint=TRUE)
\\```
---
title:
output:
pdf_document:
latex_engine: xelatex
fontsize: 11pt
#mainfont: Calibri
classoption: letter
geometry: left=0.5in, right=0.5in, top=0.6in, bottom=1.25in
subparagraph: yes
header-includes:
- \usepackage[UTF8]{ctex}
- \usepackage{setspace}
- \usepackage{tocloft}
- \usepackage{anyfontsize}
- \usepackage{fancyhdr}
- \usepackage{fontspec}
- \usepackage{sectsty}
- \sectionfont{\huge}
- \subsectionfont{\fontsize{14}{16.8}\selectfont}
- \pagestyle{fancy}
- \renewcommand{\headrulewidth}{0pt}
---
```{r}
library(ggplot2)
print("中文")
df <- data.frame(
gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))
# The summary data frame ds is used to plot larger red points on top
# of the raw data. Note that we don't need to supply `data` or `mapping`
# in each layer because the defaults from ggplot() are used.
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文")
```
After knitting this file, it seems that the character encoding works fine for the print function, but the Chinese characters do not show up in graph labels, and I get errors on character conversions. I am a Mac user.
TL;DR: This doesn't appear to be a knitr/rmarkdown issue, but rather an issue related to both the font and the output device. I'm not sure of the cause, but the workaround below involves changing the output font (Batang worked for me) and the output device (pdf is the default, but changing to cairo_pdf or png both worked for me).
First, identify a font family for which R will render the characters properly. I'm not sure in general how to determine this without trial and error, but in the past I've found that the Symbola and Batang fonts often seem to work with non-English characters and various unicode symbols. You'll need to install the fonts on your computer if you don't have them, and you also might need to use the extrafont package to register the fonts in R. Then you can run the plot code in the console and see if the Chinese characters render properly.
With the Batang font, I found that I was able to output plots to the console with the Chinese characters rendered properly. However, the standard pdf device failed to render the characters, whether saving the plot to pdf interactively or when knitting. Instead I tried the cairo_pdf and png devices and these both worked. Here's example code (using the same yaml as in your question):
```{r, include=FALSE}
knitr::opts_chunk$set(echo=FALSE)
library(ggplot2)
```
```{r, dev="cairo_pdf"}
df <- data.frame(
gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文", title="cairo_pdf device") +
#theme(axis.title.x=element_text(family="Batang")) # To change font only for x-axis title
theme(text=element_text(family="Batang", size=15))
```
```{r, dev="png", dpi=400}
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文", title="png device") +
theme(text=element_text(family="Batang", size=15))
```
And here's what the plots look like in the output document:
When including a plot with geom_col in an R Markdown report knitted to pdf, the stacked breaks between observations are made visible as gray lines:
```{r}
library(ggplot2)
ggplot(data = midwest) +
geom_col(mapping = aes(x = state, y = poptotal))
```
But when I run the exact same code directly in R Studio (or knit to HTML), the columns are shown as solid:
Is there something special to do to make the different observations not be shown in a pdf (e.g., to make the pdf-knitted plot look like the HTML-knitted one)?
Did you Try using geom_bar() instead of geom_col(), because geom_col() was created afterwards, its basically geom_bar() only
```{r}
library(ggplot2)
ggplot(data = midwest) +
geom_bar(stat="identity",mapping = aes(x = state, y = poptotal))
```
It might work, try it and let me know
You can also set fill and check what happens
geom_bar(stat="identity",mapping = aes(x = state, y = poptotal,fill="gray60"))
I am trying to achieve the following task with Knitr, ggplot2 and xtables:
Generate several annotated plots of beta-distributions with ggplot2
Write the output in a layout such that I have a plot, and a corresponding summary Stats table following it, for every plot.
Write the code such that both PDF and HTML reports can be a generated in a presentable way
Here is my attempt at this task (Rnw file):
\documentclass{article}
\begin{document}
Test for ggplot2 with Knitr
<<Initialize, echo=FALSE>>=
library(ggplot2)
library(ggthemes)
library(data.table)
library(grid)
library(xtable)
library (plyr)
pltlist <- list()
statlist <- list()
#
The libraries are loaded. Now run the main loop
<<plotloop, echo=FALSE>>=
for (k in seq(1,7)){
x <- data.table(rbeta(100000,1.6,14+k))
xmean <- mean(x$V1, na.rm=T)
xqtl <- quantile(x$V1, probs = c(0.995), names=F)
xdiff <- xqtl - xmean
dens <- density(x$V1)
xscale <- (max(dens$x, na.rm=T) - min(dens$x, na.rm=T))/100
yscale <- (max(dens$y, na.rm=T))/100
y_max <- max(dens$y, na.rm=T)
y_intercept <- y_max-(10*yscale)
data <- data.frame(x)
y <- ggplot(data, aes(x=V1)) + geom_density(colour="darkgreen", size=2, fill="green",alpha=.3) +
geom_vline(xintercept = xmean, colour="blue", linetype = "longdash") +
geom_vline(xintercept = xqtl, colour="red", linetype = "longdash") +
geom_segment(aes(x=xmean, xend=xqtl, y=y_intercept, yend=y_intercept), colour="red", linetype = "solid", arrow = arrow(length = unit(0.2, "cm"), ends = "both", type = "closed")) +
annotate("text", x = xmean+xscale, y = y_max, label = paste("Val1:",round(xmean,4)), hjust=0) +
annotate("text", x = xqtl+xscale, y = y_max, label = paste("Val2:",round(xqtl,4))) +
annotate("text", x = xmean+10*xscale, y = y_max-15*yscale, label = paste("Val3:",round(xdiff,4))) +
xlim(min(dens$x, na.rm=T), xqtl + 9*xscale) +
xlab("Values") +
ggtitle("Beta Distribution") +
theme_bw() +
theme(plot.title = element_text(hjust = 0, vjust=2))
pltlist[[k]] <- y
statlist[[k]] <- list(mean=xmean, quantile=xqtl)
}
stats <- ldply(statlist, data.frame)
#
Plots are ready. Now Plot them
<<PrintPlots, warning=FALSE, results='asis', echo=FALSE, cache=TRUE, fig.height=3.5>>=
for (k in seq(1,7)){
print(pltlist[[k]])
print(xtable(stats[k,], caption="Summary Statistics", digits=6))
}
#
Plotting Finished.
\end{document}
I am faced with several issues after running this code.
When I run this code just as R code, Once I try to print the plots in the list, the horizontal line from the geom_segment part starts to move all over the place. However if I plot the figures individually, without putting them in a list, the figures are fine, as I would expect them to be.
Only the last plot is as I would expect the output to be, in all the other plots, the geom_segment line moves around randomly.
I am also unable to put a separate caption for the Plots as I can for the Tables.
Points to note :
I am storing the beta-random numbers in data.table since in our actual code, we are using data.table. However for the purposes of testing ggplot2 in this way, I convert the data.table into a data.frame, as ggplot2 requires.
I also need to generate the random numbers within the loop and generate the plots per iteration (so something like first generating the random numbers and then using melt would not work here), since generating the random numbers is emulating a complex database call per iteration of the loop.
I am using RStudio Version 0.98.1091 and
R version 3.1.2 (2014-10-31) on Windows 8.1
This is the expected Plot:
This is the plot I am getting when plotting from the list:
My output in PDF form :
PDF Output
Please advice if there are any ideas for solutions.
Thank you,
SG
I don't know why the horizontal line in geom_segment is "moving around" from plot to plot, rather than spanning xmean to xqtl. However, I was able to get the horizontal line in the correct location by getting the value from the stats data frame, rather than from direct calculation of the mean and quantile. You just have to create the stats data frame before the loop, rather than after, so that you can use it in the loop.
stats <- ldply(statlist, data.frame)
for (k in seq(1,7)){
...
y <- ggplot(data, aes(x=V1)) +
...
geom_segment(aes(x=stats[k,1], xend=stats[k,2], y=y_intercept, yend=y_intercept),
colour="red", linetype = "solid",
arrow = arrow(length = unit(0.2, "cm"), ends = "both", type = "closed")) +
...
pltlist[[k]] <- y
statlist[[k]] <- list(mean=xmean, quantile=xqtl)
}
Hopefully, someone else will be able to explain the anomalous behavior, but at least this seems to fix the problem.
For the figure caption, you can add a fig.cap argument to the chunk where you plot the figures, although this results in the same caption for each figure and causes the figures and tables to be plotted in separate groups, rather than interleaved:
<<PrintPlots, warning=FALSE, results='asis', echo=FALSE, cache=TRUE, fig.cap="Caption", fig.height=3.5>>=
for (k in seq(1,7)){
print(pltlist[[k]])
print(xtable(stats[k,], caption="Summary Statistics", digits=6))
}
You might want to use R Markdown and knitr which is easier than using LaTeX and R (as also zhaoy suggested).
You might also want to check out the ReporteRs package. I think it is actually easier to use than knitr. However, you cannot generate PDFs with it. But you can use pandoc to convert them into PDFs.