Rmarkdown to knit html - graphs not showing - r

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).:

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)
```

How to combine outputs of different functions into a nicely report?

I have like:
. multiple plots, each created by a distinct function.
#Plot 1
sis_name <- babynames %>%
filter(name == "Kate", sex == "F") %>%
select("year", "name", "prop")
plot1 <- ggplot(data = sis_name) +
geom_line(mapping = aes(x = year, y = prop)) +
labs(title = "The Popularity of baby girls' name Kate", x =
"Year", y = "Proportion")
#Plot 2
plot2 <- ggplot(data = mydata) +
geom_point(mapping=aes(x=X, y=Y), color="blue") +
labs(title="Y vs X")
. some "text" outputs, created by glue::glue() and paste() functions.
conf_interval <- function(mydata) {
model <- lm(Y~X, data = mydata)
B_conf <- confint(model, #confidence interval for B
model$coefficients[2],
level = 0.95
glue::glue("Confidence interval for slop is {B_conf}")
}
What if I want to create a FUNCTION that calls out all the outputs (plot 1, plot 2, and the confidence interval) and combine them all into ONE nicely formatted report
(i.e. a sequence of plot and glue() commands from all the functions called sequentially)?
The requirement is to call out the report with a "function".
Any suggestions on which functions that I should look at?
You can save the example below as a file called report.Rmd:
---
title: "My Title"
author: "Me"
date: "21/08/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
suppressPackageStartupMessages(
library(tidyverse)
)
library(glue)
```
# Title
```{r}
ggplot(mpg, aes(displ, hwy)) +
geom_point()
```
Other variables include `r glue_collapse(colnames(mpg), sep = ", ", last = " and ")`.
Subsequently, you can run the following:
library(rmarkdown)
render("report.Rmd", html_document())
To produce the report.

Flex Dashboard not working when I add the world map code in it

I have created a flex dashboard using R Markdown in RStudio for 'COVID-19 WORLDWIDE TRACKER'. I have created one line plot, one area plot and 2 column graphs. I want to add a world heat map in it.
The data is here:
mydata
and
x. Code is as follows:
---
title: "COVID-19 WORLDWIDE TRACKER"
output:
flexdashboard::flex_dashboard:
orientation: rows
vertical_layout: scroll
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(ggplot2)
library(plotly)
library(readxl)
library(rworldmap)
library(dplyr)
library(maps)
library(plyr)
library(gridExtra)
x <- read_excel("owid-covid-data.xlsx")
```
Page 1
===
row {data-height = 350}
---
### World Hotspots
```{r}
library(maps)
library(ggplot2)
mydata <- readxl::read_excel("mapdata1.xlsx")
mydata$Country[mydata$Country == "United States"] <- "USA"
mydata$Country[mydata$Country == "United Kingdom"] <- "UK"
world_map <- map_data("world")
world_map <- subset(world_map, region != "Antarctica")
ggplot(mydata) +
geom_map(
dat = world_map, map = world_map, aes(map_id = region),
fill = "white", color = "#7f7f7f", size = 0.25
) +
geom_map(map = world_map, aes(map_id = Country, fill = Cases), size = 0.25) +
scale_fill_gradient(low = "#fff7bc", high = "#cc4c02", name = "Total Cases") +
expand_limits(x = world_map$long, y = world_map$lat)
```
row {data-height=300}
-----------------------------------------------------------------------
### Top 10 Countries
```{r}
p <- ggplot(x, aes(date, total_cases, color = location)) + geom_line()
ggplotly(p)
```
row {data-height=300}
-----------------------------------------------------------------------
### Daily Comparison of New Cases and Deaths
```{r}
a <- ggplot(x, aes(date, new_cases, fill = location)) + geom_area()
ggplotly(a)
```
row {data-height=400}
-----------------------------------------------------------------------
### Daily Comparison of Total Cases and Deaths
```{r}
b <- ggplot(x, aes(date, total_cases, fill = total_deaths)) + geom_col(position = "dodge")
ggplotly(b)
```
### Top Countries
```{r}
c <- ggplot(x, aes(total_cases_per_million, location)) + geom_col(position = "dodge")
ggplotly(c)
```
Without the world map code, the dashboard works perfectly fine. But when I add the world map code to it, the dashboard shows a white screen and no graphs at all. I am not able to understand why this is happening. Please help!

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:

Variable plot height within single chunk

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
```

Resources