how to add table in ggplot grid - r

I want to summary table next to the scatterplot in the final figure. The summary table should come next to the plot. Here is the sample code.
How can we do that?
Thanks
library(tidyverse)
library(cowplot)
# data
x <- runif(10000)
y <- runif(10000)
z <- c(rep(0, 5000), rep(1, 5000))
tbl <- tibble(x, y, z)
# plot
scatterplot <- ggplot(tbl,
aes(x = x,
y = y)) +
geom_point(alpha = 0.7,
size = 2) +
facet_grid(. ~ z) +
theme_bw() +
theme(aspect.ratio = 1) +
ggtitle("Scatter plot")
# add summary table
summary_tbl <- tbl %>%
group_by(z) %>%
summarise(count = n(),
x_mean = mean(x),
y_mean = mean(y))
# TASK
# to create a final plot with scatterplot and summary table in single row grid
plot_grid(scatterplot, summary_tbl,
nol = 2)

I would suggest using patchwork:
library(tidyverse)
library(cowplot)
library(patchwork)
# data
x <- runif(10000)
y <- runif(10000)
z <- c(rep(0, 5000), rep(1, 5000))
tbl <- tibble(x, y, z)
# plot
scatterplot <- ggplot(tbl,
aes(x = x,
y = y)) +
geom_point(alpha = 0.7,
size = 2) +
facet_grid(. ~ z) +
theme_bw() +
theme(aspect.ratio = 1) +
ggtitle("Scatter plot")
# add summary table
summary_tbl <- tbl %>%
group_by(z) %>%
summarise(count = n(),
x_mean = mean(x),
y_mean = mean(y))
# TASK
G <- scatterplot + gridExtra::tableGrob(summary_tbl)
Output:
You can wrap your table using gridExtra::tableGrob()
Try this for colors and order:
# TASK 2
my_table_theme <- gridExtra::ttheme_default(core=list(bg_params = list(fill = 'white', col=NA)))
#Plot
G <- scatterplot / gridExtra::tableGrob(summary_tbl,
rows = NULL,theme=my_table_theme)
Output:

Related

How to add density plot per component in PCA plot in R?

I would like to know how add density to PCA plot .
This is my basic example which i would like to begin
x <- iris[1:4]
pc <- prcomp(x)
df <- cbind(pc$x[,1:2], iris[,5]) %>% as.data.frame()
df$PC1 <- as.numeric(df$PC1) / (pc$sdev[1] * sqrt(nrow(iris)))
df$PC2 <- as.numeric(df$PC2) / (pc$sdev[2] * sqrt(nrow(iris)))
df$V3 <- as.factor(df$V3)
#ggplot method
p1 <- ggplot(df, aes(PC1, PC2, colour = V3)) +
geom_point(size = 3, aes(shape = V3)) +
stat_ellipse(geom = "polygon", aes(fill = after_scale(alpha(colour, 0))),
data = df[df$V3 == "1" | df$V3 == "2",], size = 1)
p1
Now
I would like to add similar to my plot too how to do that? Any suggestion or help would be really appreciated.
You could use the package cowplot by using insert_*axis_grob to insert two geom_density plots at the top x-axis and right y-axis. For the top x-axis density curve you can use the values of PC1 and for the right y-axis density curve you can use the values of PC2 and both color and fill them with V3. Make sure to specify the right axis for both graphs. Here is a reproducible example:
library(cowplot)
library(dplyr)
library(ggplot2)
x <- iris[1:4]
pc <- prcomp(x)
df <- cbind(pc$x[,1:2], iris[,5]) %>% as.data.frame()
df$PC1 <- as.numeric(df$PC1) / (pc$sdev[1] * sqrt(nrow(iris)))
df$PC2 <- as.numeric(df$PC2) / (pc$sdev[2] * sqrt(nrow(iris)))
df$V3 <- as.factor(df$V3)
# plot
p1 <- ggplot(df, aes(PC1, PC2, colour = V3)) +
geom_point(size = 3, aes(shape = V3)) +
stat_ellipse(geom = "polygon", aes(fill = after_scale(alpha(colour, 0))),
data = df[df$V3 == "1" | df$V3 == "2",], size = 1)
# Add density curves to y and x axis
xdens <-
axis_canvas(p1, axis = "x") +
geom_density(data = df, aes(x = PC1, fill = V3, colour = V3), alpha = 0.3)
ydens <-
axis_canvas(p1, axis = "y", coord_flip = TRUE) +
geom_density(data = df, aes(x = PC2, fill = V3, colour = V3), alpha = 0.3) +
coord_flip()
p1 %>%
insert_xaxis_grob(xdens, grid::unit(1, "in"), position = "top") %>%
insert_yaxis_grob(ydens, grid::unit(1, "in"), position = "right") %>%
ggdraw()
Created on 2022-08-31 with reprex v2.0.2

Time series bar graph reordering

I have the following script I'm working on, I want to re order the bar graph in descending order by their values.
library(tidyverse)
library(lubridate)
library(ggplot2)
#df <- read_csv('dataframe.csv')
df %>%
mutate(date=mdy(date), year=year(date), year = year + (date >= mdy(paste0("10/01/", year))))%>%
group_by(year) %>%
summarize(avg = mean(flow)) -> df
y <- df$avg
x <- ymd(sprintf("%d-01-01",df$year))
d <- data.frame(x = x, y = y)
# interpolate values from zero to y and create corresponding number of x values
vals <- lapply(d$y, function(y) seq(0, y, by = 0.1))
y <- unlist(vals)
mid <- rep(d$x, lengths(vals))
d2 <- data.frame(x = mid - 100,
xend = mid + 100,
y = y,
yend = y)
ggplot(data = d2, aes(x = x, xend = xend, y = y, yend = yend, color = y)) +
geom_segment(size = 2)
Results
I want to reorder the bars in descending order by values
The dataset can be found through the following link
https://drive.google.com/file/d/11PVub9avzMFhUz02cHfceGh9DrlVQDbD/view?usp=sharing
the output I'm looking for is like this.
Kindly assist.
To arrange the data you need to adjust the factor levels. You could arrange the data based on avg column and change year to factor.
library(dplyr)
library(ggplot2)
df %>%
arrange(desc(avg)) %>%
mutate(year = factor(year, unique(year))) %>%
ggplot() + aes(year, avg) + geom_col(aes(fill = 'red')) + guides(fill=FALSE)
Or :
df %>%
arrange(desc(avg)) %>%
mutate(year = factor(year, unique(year))) %>%
ggplot() + aes(year, avg, fill = avg) + geom_col()
Try this:
library(scales)
#Custom Transform function
dttrans <- function(a, b, breaks = b$breaks, format = b$format) {
a <- as.trans(a)
b <- as.trans(b)
name <- paste(a$name, b$name, sep = "-")
trans <- function(x) a$trans(b$trans(x))
inv <- function(x) b$inverse(a$inverse(x))
trans_new(name, trans, inv, breaks, format = format)
}
ggplot(data = d2, aes(x = x, xend = xend, y = y, yend = yend, color = y)) +
geom_segment(size = 2) +
scale_x_continuous(trans = dttrans("reverse", "date"))
Credits: Mikko Marttila

Plot some points in contour curve from ggplot2

I'd like to plot a specific number of points of z in the contour curve, for example, 8 or 10 points. Below I show an example, but with all points.
library(ggplot2)
library(tidyverse)
rosenbrock <- function(x){
d <- length(x)
out <- 0
for(i in 1 : (d - 1)){
out <- out + 100 * ( x[i]^2 - x[i + 1] )^2 + (x[i] - 1)^2
}
out
}
set.seed(2020)
coord <- matrix(runif(2000, -100, 100), ncol = 2)
graph <- apply(coord, 1, rosenbrock)
results <- data.frame(x = coord[, 1], y = coord[, 2], z = graph)
results <- results %>% arrange(desc(z))
results %>%
ggplot(aes(x = x, y = y, z = z)) +
geom_point(aes(colour = z)) +
stat_density2d() +
theme_light()
You can set the alpha to equal zero when you originally plot the points, and then filter the data to include the points that you want (here, I just took a random sample):
results %>%
ggplot(aes(x = x, y = y, z = z)) +
geom_point(aes(colour = z), alpha=0) +
stat_density2d() +
geom_point(data = sample_n(results, 10), aes(colour = z)) +
theme_light()

How to put variables in legend in ggplot2

I want to get the following plot.
So, how would I put a variable i.e. cov(x,y) as string in legend using ggplot?
I would recommend calculating the covariance in a separate data frame, and customizing the color scale using the values in the covariance data frame:
Sample Data
library(dplyr)
library(ggplot2)
set.seed(999)
d <- data.frame(
x = runif(60, 0, 100),
z = rep(c(0, 1), each = 30)
) %>%
mutate(
y = x + 50 * z + rnorm(60, sd = 50),
z = factor(z)
)
Here is the basic plot, with a separate color for each value of z:
ggplot(d, aes(x = x, y = y, color = z)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE)
Now create a smaller data frame that contains covariance values:
cov_df <- d %>%
group_by(z) %>%
summarise(covar = round(cov(x, y)))
Extract the covariance values and store as a character vector:
legend_text <- as.character(pull(cov_df, covar))
Control the color scale to achieve your desired outcome:
ggplot(d, aes(x = x, y = y, color = z)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE) +
scale_color_discrete(
"Covariance",
labels = legend_text
)

Common legend for several geom area ggplot

I created a plot with several geom_area according to the following code :
library(ggplot2)
set.seed(1)
dat <- data.frame(matrix(rnorm(100, 10, 2), 100, 1))
dat_density <- data.frame(density(dat[, 1])[c("x", "y")])
quant <- quantile(dat[, 1], probs = seq(0, 1, 0.10))
library(RColorBrewer)
color_pal <- brewer.pal(length(quant)-1, "RdYlBu")
dens <- ggplot(data = dat_density, aes(x = x, y = y)) +
geom_line(size = 2)
for(i in 1:(length(color_pal))){
dens <- dens +
geom_area(data = subset(dat_density, x > quant[[i]] & x < quant[[i + 1]]), fill = color_pal[i])
}
dens
How can I add a common legend with each color of the color_pal vector (corresponding to all the 10% area of data) ?
The easiest way is to define the groups in your dataset
dat_density$quant <- cut(dat_density$x, breaks = c(-Inf, quant, Inf))
ggplot(data = dat_density, aes(x = x, y = y, fill = quant)) +
geom_line(size = 2) +
geom_area() +
scale_fill_brewer(palette = "RdYlBu")

Resources