ggplot Custom fonts not working in Quarto - r

When I render a ggplot with custom fonts it works in the IDE however in Quarto and RMarkdown I keep getting this error:
Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
invalid font type
Calls: .main ... drawDetails -> drawDetails.text -> grid.Call.graphics
The fonts are all installed on my system, but not recognized by Quarto or RMakrdown.
For example, here is my script:
---
title: "TEST"
format: pdf
editor: visual
---
This plot works:
```{r echo=FALSE, message=FALSE, warning=FALSE}
library(tidyverse)
mtcars |>
count (cyl) |>
ggplot (aes (x = cyl, y = n)) +
geom_col() +
labs (title = "Plot 1") +
geom_text (aes (label = n),
vjust = -1)
```
This plot does not:
```{r echo=FALSE, message=FALSE, warning=FALSE}
mtcars |>
count (cyl) |>
ggplot (aes (x = cyl, y = n)) +
geom_col() +
labs (title = "Plot 2") +
geom_text (aes (label = n),
vjust = -1,
family = "Montserrat") +
theme (text = element_text(size = 12, family = "Montserrat"))
```

Missed a step. I added
extrafont::loadfonts(quiet = TRUE)
At the beginning of the script and it works now.

Related

ggiraph plot not rendering on Quarto (RStudio viewer)

I have made a plot with an interactive annotation; this works in RStudio in the viewer tab when I run this code:
library(ggiraph)
library(tidyverse)
data(iris)
graph <- iris %>%
ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
annotate_interactive("text", x = 7, y = 4,
label = "1.",
fontface = "bold",
tooltip = "a test")
girafe(ggobj = graph)
RStudio viewer tab:
However, when I try to write this onto a Quarto document and render in Rstudio, the graph comes back as a blank space. It doesn't load. The output is html.
library(ggiraph)
library(tidyverse)
data(iris)
graph <- iris %>%
ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
annotate_interactive("text", x = 7, y = 4,
label = "1.",
fontface = "bold",
tooltip = "a test")
girafe(ggobj = graph)
I would have expected this to work within Quarto, but I might be missing something. Many thanks.
I have solved my own question. Orginally I had written near the top of the file cache = TRUE. I replaced this with echo = TRUE. Now it works
```{r setup, include = FALSE}
knitr::opts_chunk$set(cache = TRUE)
```
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Is there a function for adjusting the size of my ggplot chart in R

I am trying to increase the size of my ggplot chart:
And I tried this:
ggplot(accident_day, aes(year, accidents, group = 1)) +
geom_point() +
geom_line() +
labs(title = "THE RATE OF ACCIDENTS", x = "Year", y = "Number of Accidents")+
theme(figure.width = 8, figure.height = 4)
and also this :
theme(plot.width = 10, plot.height = 5)
But got this output:
Error in `mapply()`:
! The `plot.width` theme element is not defined in the element hierarchy.
Run `rlang::last_error()` to see where the error occurred.
Assuming you mean the output of the plot in the HTML markdown file, you can use the following argument in the code chunk's header:
```{r fig.height=10, fig.width=10}
ggplot(accident_day, aes(year, accidents, group = 1)) +
geom_point() +
geom_line() +
labs(title = "THE RATE OF ACCIDENTS", x = "Year", y = "Number of Accidents")
```
You can also set the default size of the plots in the knitr setup chunk like so:
```{r}
knitr::opts_chunk$set(
fig.width=10,
fig.height=10)
```

HOLD_position argument and related solutions don't work with 4th level header

I am working on a somewhat large report, where I produce data tables and figures in r and then use rmarkdown to compile those results into a pdf report. Normally I do not have issues making tables/figures appear where I want them (HOLD_position does the trick), but I discovered that the normal trick does not work for some reason where a 4th level header is concerned.
Attaching a reproducible example, first making a figure and tables in R:
data("iris")
library(ggplot2)
# plots with numbered titles to help track in document
p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + theme_bw() +
geom_smooth() + ggtitle("Plot 1")
png('mock1.png', res = 600, width = 3, height = 4, units = 'in')
print(p)
dev.off()
p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + theme_bw() +
geom_smooth() + ggtitle("Plot 2")
png('mock2.png', res = 600, width = 3, height = 4, units = 'in')
print(p)
dev.off()
p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + theme_bw() +
geom_smooth() + ggtitle("Plot 3")
png('mock3.png', res = 600, width = 3, height = 4, units = 'in')
print(p)
dev.off()
write.csv(iris[1:30,], file = "table.csv")
Now an rmd which produces figures/tables that are out of order with respect to the 4th level headers (#### 4th level header)
title: "I broke HOLD_position"
author: "cdtip"
date: "3/1/2022"
output: pdf_document
---
# 1st level heading
## 2nd level heading
### 3rd level heading
#### 4th: set 1
```{=latex}
\begin{figure}[H]
\centering
\includegraphics[width=14 cm]{mock1}
\caption{Caption for mock fig.}
\end{figure}
```
```{r echo=FALSE, results='asis'}
suppressWarnings(library(kableExtra, quietly = T))
tab = read.csv(file = "table.csv", header = T, check.names = F)
kbl(tab, caption = "Table 1", booktabs = T) %>%
kable_styling(latex_options = c("HOLD_position"))
```
#### 4th: set 2
```{=latex}
\begin{figure}[H]
\centering
\includegraphics[width=14 cm]{mock2}
\caption{Caption for mock fig.}
\end{figure}
```
```{r echo=FALSE, results='asis'}
suppressWarnings(library(kableExtra, quietly = T))
tab = read.csv(file = "table.csv", header = T, check.names = F)
kbl(tab, caption = "Table 2", booktabs = T) %>%
kable_styling(latex_options = c("HOLD_position"))
```
#### 4th: set 3
```{=latex}
\begin{figure}[H]
\centering
\includegraphics[width=14 cm]{mock3}
\caption{Caption for mock fig.}
\end{figure}
```
```{r echo=FALSE, results='asis'}
suppressWarnings(library(kableExtra, quietly = T))
tab = read.csv(file = "table.csv", header = T, check.names = F)
kbl(tab, caption = "Table 3", booktabs = T) %>%
kable_styling(latex_options = c("HOLD_position"))
```
If you follow the code provided and assuming my issue is reproducible, you should produce a pdf where the tables and figures are placed whereever the mystical pdf float gods decided to place them, and NOT in the order I specified. Now, if you repeat that same .rmd portion, but change the 4th level to 3rd level headers (e.g., #### to ###), the items should be placed correctly.
I've tried a few solutions proposed for similar issues:
Empty line placement
How to I keep kable from formatting text that follows the table?
Latex-based solution
R Markdown, kable_styling(latex_options="HOLD_position") not working
Read through kableExtra and other reference materials as well, but
not seeing something that seems to address this specific issues.
For the immediate project it is fine to just use 3rd level headings, but I don't like how this in turn affects the ToC as I now have several appended names to mark the differences in what previously would have been under different 3rd level categories. Can this be fixed in order to use 4th level headers?

Rmarkdown to knit html - graphs not showing

I have the following lines of code:
ggplot(data = subset(gapminder1, year %in% c(seq(1900, 1990, by = 10))), aes(x = year, y = lifeExp)) + geom_boxplot(aes(group = year))
ggplot(subset(gapminder1,country=="United States"),aes(x = year, y = lifeExp)) + geom_line()
ggplot(subset(gapminder1,country %in% c("China","India","United States","Indonesia","Brazil")) , aes(x = year, y = lifeExp)) + geom_line(aes(color=country))
The graphs show up fine in the rmd file when I run the code. However, when I knit the document the graphs do not show up (a blank graph comes up). Can anyone tell me what I could do?
Please see the code below knitted into HTML file:
---
title: "check"
author: "Artem"
output:
html_document: default
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
Check graph
```{r gapminder, echo=FALSE}
gapminder <- read.csv("https://raw.githubusercontent.com/birdsarah/pydata-nc/master/tutorial/assets/gapminder.csv", header = TRUE)
gapminder1 <- setNames(gapminder, c(c("country", "year", "lifeExp", "population", "income", "region"
)))
library(ggplot2)
gpm_sub <- subset(gapminder1, country %in% c("China","India","United States","Indonesia","Brazil"))
g1 <- ggplot(gpm_sub, aes(x = year, y = lifeExp)) +
geom_line(aes(color=country))
gpm_sub_us <- subset(gapminder1,country=="United States")
g2 <- ggplot(gpm_sub_us,aes(x = year, y = lifeExp)) +
geom_line()
g3 <- ggplot(gpm_sub, aes(x = year, y = lifeExp)) +
geom_line(aes(color=country))
library(gridExtra)
grid.arrange(g1, g2, g3, nrow = 2)
```
Output (No problems experienced).:

A Kableextra table and a ggplot plot on same row in Rmarkdown (PDF - not Flexdashboard)

I have been experimenting with R Markdown to create some PDF reports. I am having difficulty in getting the layout right. Basically, I need to have a KableExtra created table (dataframe) and a ggplot plot on the same row. I have explored some grid packages, but couldn't get it to work.
Here is my code:
---
title: "Untitled"
author: ""
date: "14 June 2018"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(reshape2)
library(dplyr)
library(kableExtra)
```
## R Markdown
```{r chart, echo=FALSE}
Years <- c("2016","2016","2016","2016",
"2017","2017","2017","2017")
Quarters <- c("Q1","Q2","Q3","Q4",
"Q1","Q2","Q3","Q4")
Series1 <- c("100","200","300","400","500","600","700","800")
Series1 <- as.numeric(Series1)
df <- data.frame(Years,Quarters, Series1)
library(ggplot2)
ggplot(df) +
geom_point(aes(x = Quarters, y = Series1)) +
facet_wrap( ~ Years, strip.position = "bottom",scales = "free_x") +
theme(panel.spacing = unit(0,"lines"), strip.background =
element_blank(),
strip.placement = "outside")
```
```{r table, echo=FALSE}
Table <- dcast(df, Years ~ Quarters, fun.aggregate = sum, value.var =
"Series1")
Table <- Table %>%
kable(format = "latex", caption = "Balances", booktabs = TRUE) %>%
kable_styling(latex_options = c("striped","hold_position","condensed"),
font_size = 10)
Table
```
If you are not strongly depending on kable() I can provide this gridExtra solution. When using tableGrob(kable(.)) the latex code won't be executed somehow, maybe somebody else comes up with how to execute latex code within a tableGrob().
```{r chart, echo=FALSE, message=FALSE}
df <- data.frame(Years=rep(2016:2017, each=4),
Quarters=rep(paste0("Q", 1:4), 2),
Series1=seq(100, 800, 100))
library(ggplot2)
p1 <- ggplot(df) +
geom_point(aes(x=Quarters, y=Series1)) +
facet_wrap( ~ Years, strip.position="bottom", scales="free_x") +
theme(panel.spacing=unit(0, "lines"),
strip.background=element_blank(),
strip.placement="outside",
aspect.ratio=1) # set aspect ratio
Table <- dcast(df, Years ~ Quarters, fun.aggregate=sum, value.var="Series1")
library(gridExtra)
t1 <- tableGrob(Table, theme=ttheme_minimal(), rows=NULL) # transform into a tableGrob
grid.arrange(p1, t1, nrow=1)
```
Produces:

Resources