How to add notes to a ggplot - r

I would like to write some notes under my ggplot. I did my data analysis in R and using now the markdown package to write my thesis. This means I can easily include variables in the markdown script. In that script I create some ggplots and was wondering if there is an easy way to write those explanations to the plot. For tables, it is pretty straight forward. %>% footnote(general="") does the trick.
Is there something like that for plots?

Perhaps you are looking for something like this?
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + labs(title = "Your title", caption = "Your long reference footnote goes in here")
You need to use the caption parameter from labs() function.
Example:

Since you mentioned you are writing a thesis, I found the following helpful. You can insert a code chunk along the following lines:
```{r, fig.cap = "\\label{fig:myfigure} Here be your caption text"}
generate_a_figue(my_data)
```
Then, in the main text of your markdown text you could refer to your figure as follows (Figure \ref{fig:myfigure})

Also you could left align or center align your caption by adding:
``` + theme(plot.caption=element_text(hjust = int)
For left align : hjust = 0
For center align: hjust = 0.5
For right align : hjust = 1

Related

R Markdown density plot error using kable [duplicate]

I have created a plot with ggplot2 where the x-axis labels are not readable unless the plot is larger than default. When viewing in Rstudio I am able to resize dynamically. When saving with ggsave() I am able to specify height and width. How would I do this within the Rmarkdown file so that the output contains a plot of the desired size?
You can specify height and width in the code chunks
```{r, fig.width=10,fig.height=11}
df %>% ggplot(aes(x = x, y = y)) + geom_point()
```
As a side-answer, note that you can also use metric-system units using ggplot2::unit():
library(ggplot2)
knitr::opts_chunk$set(fig.width=unit(18,"cm"), fig.height=unit(11,"cm"))
If you would like to do this for all plots then you can use the r setup Rmd chunk at the beginning of the file.
knitr::opts_chunk$set(echo = TRUE, fig.width = 10, fig.height = 5)

Automatic line break in ggtitle

Is there a way to force an automatic line break in the ggtitle command?
As part of a shiny application I use different plots with an input variable for the title.
Unfortunately, some of these variable values are too long to be displayed.
I came across one possibility by inserting \n (or a line break) manually in advance (Details here: Improve editing of multiline title in ggplot that uses \n and extends far to the right). There, something like ggtitle(paste("", title, "", sep = "\n")) would be suggested.
Since including \n would be error prone as well as not flexible for different plot sizes I´m looking for another possibility.
Here is an minimal working example (adapted from lawyeR question linked above):
DF <- data.frame(x = rnorm(400))
title_example <- "This is a very long title describing the plot in its details. The title should be fitted to a graph, which is itself not restricted by its size."
plot <- ggplot(DF, aes(x = x)) + geom_histogram() +
ggtitle(title_example)
You can find a image here: https://i.stack.imgur.com/6MMKF.jpg
Do you have an idea how to e.g. adapt the sep = operator to break lines automatically or are there maybe packages/ workarounds? Thanks!
The ggtext package's text elements could help solve this. element_textbox_simple() automatically wraps the text inside. Try resizing the graphics device window, it adapts!
library(ggplot2)
library(ggtext)
DF <- data.frame(x = rnorm(400))
title_example <- "This is a very long title describing the plot in its details. The title should be fitted to a graph, which is itself not restricted by its size."
ggplot(DF, aes(x = x)) + geom_histogram() +
ggtitle(title_example) +
theme(plot.title = element_textbox_simple())
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Plots are squished when exporting to .pptx using officer

I'm using the officer package to write ggplots to Powerpoint, and even though my plots look good in my Rstudio viewer, my plots are getting "squished" when I add them to any custom slide with smaller content boxes.
I did my best to reproduce my issue with the following code:
library(tidyverse)
library(officer)
p <- data.frame(x = rnorm(100)) %>%
ggplot() +
geom_density(aes(x)) +
labs(title = "This is a title") +
annotate("text", x = 0, y = 0.2, label = "This is some text")
read_pptx("~/Downloads/template.pptx") %>%
add_slide(layout = "Title and Content") %>%
ph_with(p, location = ph_location_type("body", id = 1)) %>%
add_slide(layout = "text_example") %>%
ph_with(p, location = ph_location_type("body", id = 1)) %>%
print("~/Desktop/test_example.pptx")
Where template.pptx is a copy of the officer template with the "Title and Content" slide duplicated (and named "test_example") and content box shrunken down a little bit (available here for reproducibility).
The first slide looks good, like this:, but the second slide has the dimensions of the plot shrunken while the content in the plot stays the same size, giving it a "squished" feel:
Has anyone run into this before? Are there any tricks/hacks out there that can tell my plot to decrease the size of all it's elements when the total image space is decreased? I'd like to maintain the relative size of the elements of the plot as I move to different slide templates.
If you're still here - THANK YOU FOR READING SO FAR! I'd appreciate any and all tips :)
Here is the code that would avoid that problem with officer version 0.3.14 or later (I haven't update my package for a while and officer is an on-going package)
For better quality plot with smaller size using vector graphic instead. Using package rvg
library(rvg)
library(gridExtra)
document %<>%
add_slide(layout = "text_example") %>%
# add the plot in at position relative to 1 inches top left
# with size is 6 inches square
# grid.arrange is just a code for generate plot not actually arrange anything
ph_with(value = dml(code = grid.arrange(plot), bg = "transparent"),
location = ph_location(left=1, top=1, width=6,
height=6, bg="transparent")) %>%
# Add a text box on the right side of the slide with certain
# size & colors
ph_with(value = block_list(fpar(ftext(" "))),
location = ph_location(left=6.11, top=1, width=3.73,
height=3.3, bg="#C6D9F1"))
I would recommend this when working with Powerpoint otherwise, you need to adjust template in Powerpoint and remember the order of each content container in that slide

Specify height and width of ggplot graph in Rmarkdown knitr output

I have created a plot with ggplot2 where the x-axis labels are not readable unless the plot is larger than default. When viewing in Rstudio I am able to resize dynamically. When saving with ggsave() I am able to specify height and width. How would I do this within the Rmarkdown file so that the output contains a plot of the desired size?
You can specify height and width in the code chunks
```{r, fig.width=10,fig.height=11}
df %>% ggplot(aes(x = x, y = y)) + geom_point()
```
As a side-answer, note that you can also use metric-system units using ggplot2::unit():
library(ggplot2)
knitr::opts_chunk$set(fig.width=unit(18,"cm"), fig.height=unit(11,"cm"))
If you would like to do this for all plots then you can use the r setup Rmd chunk at the beginning of the file.
knitr::opts_chunk$set(echo = TRUE, fig.width = 10, fig.height = 5)

Modify external R script in a knitr chunk

I'm wondering if it's possible to hook into the code in an external R script that is read by knitr.
Specifically, say that you have the following R file
test.R
## ---- CarPlot
library(ggplot2)
CarPlot <- ggplot() +
stat_summary(data = mtcars,
aes(x = factor(gear),
y = mpg
),
fun.y = "mean",
geom = "bar"
)
CarPlot
Imagine that you wanted to use this graph in multiple reports, but in one of these reports you want the graph to have a title and in the other report you do not.
Ideally, I would like to be able to use the same external R script to be able to do this so that I do not have to make changes to multiple R files in case I decide to change something about the graph.
I thought that one way to perhaps do this would be by setting the fig.show chunk option to hold—since it will "hold all plots and output them in the very end of a code chunk"—and then appending a title to the plot like so:
test.Rnw
\documentclass{article}
\begin{document}
<<external-code, cache=FALSE,echo=FALSE>>=
read_chunk('./test.R')
#
<<CarPlot,echo=FALSE,fig.show='hold'>>=
CarPlot <- CarPlot + ggtitle("Plot about cars")
#
\end{document}
This, however, does not work. Although the plot is printed, the title that I tried to append does not show up.
Is there some way to do what I would like to do?
You don't want to show the plot created by test.R, so you should set fig.show = 'hide' or include = FALSE for that chunk:
<<external-code, cache=FALSE,echo=FALSE,fig.show = 'hide'>>=
read_chunk('./test.R')
#
You do want to show the plot after modification, so you have to print it:
<<CarPlot,echo=FALSE>>=
CarPlot <- CarPlot + ggtitle("Plot about cars")
CarPlot
#
fig.show = 'hold' is used if you have a large code chunk that prints a plot in the middle, but you don't want the plot to show in your document until the end. It doesn't apply to this case.

Resources