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)
```
Related
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)
```
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.
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?
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).:
The following knitr thingy produces multiple plots via lapply. Their number and content therefore varies depending on the preceding R code.
Is there a way to set the plot height individually for each plot using a variable (like the height of the highest bar in a given bar chart)?
---
title: "Variable plot height"
output: word_document
---
Plots:
```{r, echo=FALSE, fig.height = 2}
library(ggplot2)
library(tidyr)
data(mtcars)
mtcars$car = row.names(mtcars)
cars = gather(mtcars[1:5, ], variable, value,
-c(car, mpg, disp, hp, qsec))
lapply(unique(cars$car), function(x) {
ggplot(cars[cars$car == x, ], aes(variable, value)) +
geom_bar(stat = "identity")
})
```
One way would be to create each image and include it into the document as an external image. You can employ the power of "asis". Here's a small example.
---
title: "Untitled"
author: "Neznani partizan"
date: "04. december 2015"
output: html_document
---
```{r, echo=FALSE, fig.height = 2}
library(ggplot2)
library(tidyr)
data(mtcars)
mtcars$car = row.names(mtcars)
cars = gather(mtcars[1:5, ], variable, value,
-c(car, mpg, disp, hp, qsec))
suppressMessages(invisible(lapply(unique(cars$car), function(x) {
ggplot(cars[cars$car == x, ], aes(variable, value)) +
geom_bar(stat = "identity")
ggsave(sprintf("%s.png", x))
})))
```
```{r results = "asis", echo = FALSE}
cat(sprintf("<img src='%s' alt='' style='width:350px;height:228px;'> <br />",
list.files(pattern = ".png", full.name = TRUE)))
```
Image sizes can be adjusted on-the-fly using appropriate arguments in ggsave and/or in printing HTML code.
The fig.width and fig.height chunk options can take in multiple values. In your example, there are five plots, so by setting a numeric vector of length five for the widths and heights, and saving the list of ggplot objects, you can have one chunk produce five graphics of different sizes in the final document. An example .Rmd file is below.
---
title: "Variable plot height"
output: word_document
---
Plots:
```{r, echo=FALSE}
library(ggplot2)
library(tidyr)
data(mtcars)
mtcars$car = row.names(mtcars)
cars = gather(mtcars[1:5, ], variable, value, -c(car, mpg, disp, hp, qsec))
plots <-
lapply(unique(cars$car), function(x) {
ggplot(cars[cars$car == x, ], aes(variable, value)) +
geom_bar(stat = "identity")
})
widths <- c(3, 4, 5, 3, 6)
heights <- c(3, 3, 3, 4, 3)
```
```{r show_plots, fig.width = widths, fig.height = heights}
plots
```