Dynamically switch to next tab in flexdashboard - r

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.

Related

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.

ggplot2: same bar widths when saving pdf

I want all bars to have the same width.
My code works when not saving it to a pdf:
library(ggplot2)
dat <- as.data.frame(mtcars)
# convert rownames to a separate column
dat <- cbind(rownames(dat), data.frame(dat, row.names=NULL))
names(dat)[which(names(dat) == "rownames(dat)")] <- "type"
p <- ggplot(data=dat[1:10,]) +
geom_col(aes(x = reorder(type, wt), y = wt), position=position_dodge2(width = 0.1, preserve = "single"), width = 0.1) +
coord_flip()
p
But when I try to save the plot in a pdf, then the bars have slightly different widths.
pdf(paste0(path_out,
"test.pdf"),
width=10, height=4)
print(p)
dev.off()
With my real data it is even worse:
I am using Windows 7 Enterprise. How can I fix this?

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:

ggplot2 Scatter Plot Labels

I'm trying to use ggplot2 to create and label a scatterplot. The variables that I am plotting are both scaled such that the horizontal and the vertical axis are plotted in units of standard deviation (1,2,3,4,...ect from the mean). What I would like to be able to do is label ONLY those elements that are beyond a certain limit of standard deviations from the mean. Ideally, this labeling would be based off of another column of data.
Is there a way to do this?
I've looked through the online manual, but I haven't been able to find anything about defining labels for plotted data.
Help is appreciated!
Thanks!
BEB
Use subsetting:
library(ggplot2)
x <- data.frame(a=1:10, b=rnorm(10))
x$lab <- letters[1:10]
ggplot(data=x, aes(a, b, label=lab)) +
geom_point() +
geom_text(data = subset(x, abs(b) > 0.2), vjust=0)
The labeling can be done in the following way:
library("ggplot2")
x <- data.frame(a=1:10, b=rnorm(10))
x$lab <- rep("", 10) # create empty labels
x$lab[c(1,3,4,5)] <- LETTERS[1:4] # some labels
ggplot(data=x, aes(x=a, y=b, label=lab)) + geom_point() + geom_text(vjust=0)
Subsetting outside of the ggplot function:
library(ggplot2)
set.seed(1)
x <- data.frame(a = 1:10, b = rnorm(10))
x$lab <- letters[1:10]
x$lab[!(abs(x$b) > 0.5)] <- NA
ggplot(data = x, aes(a, b, label = lab)) +
geom_point() +
geom_text(vjust = 0)
Using qplot:
qplot(a, b, data = x, label = lab, geom = c('point','text'))

Resources