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.
Related
I have around 20 sample for which I need to plot graphics such as histograms, boxplots, etc... I would like to organise all these plots in a flexdashboard where I would have one tab per sample. So each tab has one histogram, one boxplot, etc.
The below template produces only one tab. I doubled the dataset and add a column so it has two type, "first_sample" & "second_sample" (first chunk of code).
Is there an easy way to loop on these types so it generates the plots on seperated tabs for each sample ?
Thanks !
Edit : I also found this post but I couldn't make it work : Dynamicly increasing amount of tabs and pages in flexdashboards
---
title: "ggplotly geoms"
author: "Carson Sievert"
output:
flexdashboard::flex_dashboard:
orientation: rows
social: menu
source_code: embed
---
```{r setup, include=FALSE}
library(ggplot2)
library(plotly)
library(plyr)
library(flexdashboard)
# Make some noisily increasing data
set.seed(955)
dat1 <- data.frame(cond = rep(c("A", "B"), each=10),
xvar = 1:20 + rnorm(20,sd=3),
yvar = 1:20 + rnorm(20,sd=3))
dat1$type <- "first_sample"
dat2 <- data.frame(cond = rep(c("A", "B"), each=10),
xvar = 1:20 + rnorm(20,sd=3),
yvar = 1:20 + rnorm(20,sd=3))
dat2$type <- "second_sample"
dat <- rbind(dat1, dat2)
```
geom_point
=======================================================================
Row
-----------------------------------------------------------------------
### Scatter Chart with geom_point
```{r}
p <- ggplot(dat, aes(x=xvar, y=yvar)) +
geom_point(shape=1) # Use hollow circles
ggplotly(p)
```
### geom_smooth Linear Regression
```{r}
p <- ggplot(dat, aes(x=xvar, y=yvar)) +
geom_point(shape=1) + # Use hollow circles
geom_smooth(method=lm) # Add linear regression line
ggplotly(p)
```
Row
-----------------------------------------------------------------------
### geom_smooth with Loess Smoothed Fit
```{r}
p <- ggplot(dat, aes(x=xvar, y=yvar)) +
geom_point(shape=1) + # Use hollow circles
geom_smooth() # Add a loess smoothed fit curve with confidence region
ggplotly(p)
```
### Constraining Slope with stat_smooth
```{r}
n <- 20
x1 <- rnorm(n); x2 <- rnorm(n)
y1 <- 2 * x1 + rnorm(n)
y2 <- 3 * x2 + (2 + rnorm(n))
A <- as.factor(rep(c(1, 2), each = n))
df <- data.frame(x = c(x1, x2), y = c(y1, y2), A = A)
fm <- lm(y ~ x + A, data = df)
p <- ggplot(data = cbind(df, pred = predict(fm)), aes(x = x, y = y, color = A))
p <- p + geom_point() + geom_line(aes(y = pred))
ggplotly(p)
```
To do this I had to combine (and I am citing some of this post) :
Use loop to generate section of text in rmarkdown
sprintf to prepare template text and name tabs by the types of data
results = "asis", rmarkdown chunk parameter "to prevent knitr from adding formatting to the output"
cat to prevent R from adding additional stuff like quotes and element numbers"
print to plot in for loops
The following code produces a flexdashboard with two tabs and two plots for each sample in dat
---
title: "test"
author: "Paul Endymion"
output:
flexdashboard::flex_dashboard:
orientation: rows
social: menu
source_code: embed
---
```{r setup, include=FALSE}
library(ggplot2)
library(flexdashboard)
library(data.table)
# Make some noisily increasing data
set.seed(955)
dat1 <- data.frame(cond = rep(c("A", "B"), each=10),
xvar = 1:20 + rnorm(20,sd=3),
yvar = 1:20 + rnorm(20,sd=3))
dat1$type <- "first_sample"
dat2 <- data.frame(cond = rep(c("A", "B"), each=10),
xvar = 1:20 + rnorm(20,sd=3),
yvar = 1:20 + rnorm(20,sd=3))
dat2$type <- "second_sample"
dat <- rbind(dat1, dat2)
setDT(dat)
```
```{r echo = FALSE, results = "asis"}
template <- "
%s
=======================================================================
### Scatter Chart with geom_point
" # dont't forget the newline
template2 <- "
Row
-----------------------------------------------------------------------
### geom_smooth Linear Regression
"
for (i in unique(dat$type)) {
cat(sprintf(template, i))
p<-ggplot(dat[type == i], aes(x=xvar, y=yvar)) +
geom_point(shape=1) # Use hollow circles
print(p)
cat(template2)
p2 <- ggplot(dat[type == i], aes(x=xvar, y=yvar)) +
geom_point(shape=1) + # Use hollow circles
geom_smooth(method=lm) # Add linear regression line
print(p2)
}
```
It still needs tuning but it does what I wanted to do.
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!
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).:
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:
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
```