How to add basemaps to spatraster plot with ggplot 2? - r

I want to add this basemap using to raster using ggplot2 and terra packages and I am stuck.
Can I have some help figuring this out?
library(basemaps)
library(terra)
Library(rasterVis)
set_defaults(Yiel_total , map_service = "esri" , map_type = "world_hillshade")
x <- basemap_magic(Yiel_total , map_service = "esri" , map_type = "world_hillshade")
#Yiel_total was used for the extent
SpatRaster Data for Yiel_total
The ggplot code:
Yield <-rast("Yield_total")
Yield_Tot_6 <- gplot(Yield ) + geom_tile(aes(fill = value)) + ggtitle("")+
theme(panel.spacing.x=unit(0,"lines"), axis.title.x = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(),
axis.title.y = element_blank(),plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),strip.background = element_blank(),
strip.text = element_text(size = 14, color = "black", face = "bold"),legend.text = element_text(size = 14, face = "bold"),
legend.title = element_text(hjust = 0.1, size = 16, face = "bold"), panel.background = element_blank()) +
guides(fill = guide_colourbar(title = "Relative yield",title.hjust = 0.5, barheight = 15, barwidth = 2))+
#basemap_magic(Yield_0.5_6, map_service = "esri" , map_type = "world_hillshade")+
facet_wrap(~ variable, ncol = 3 ) +
scale_fill_gradient(limits = c(0.01,0.88),low = 'red', high = 'dark green', na.value = "grey93", breaks = c(0.02,0.20, 0.40, 0.60,0.75, 0.87))
Yield_Tot_6

You can use tidyterra to work easily with ggplot2 and SpatRasters. I modified the call to basemap_raster and converted it also to SpatRaster:
library(basemaps)
library(terra)
Yiel_total <- rast("Yiel_total.tif")
set_defaults(Yiel_total, map_service = "esri", map_type = "world_hillshade")
x <- basemap_raster(Yiel_total, map_service = "esri", map_type = "world_hillshade")
x_terr <- rast(x)
library(ggplot2)
library(tidyterra)
ggplot() +
geom_spatraster_rgb(data = x_terr) +
geom_spatraster(data = Yiel_total) +
# Faceting with tidyterra
facet_wrap(~lyr, ncol = 3) +
scale_fill_gradient(
limits = c(0.01, 0.88), low = "red", high = "dark green",
na.value = NA, breaks = c(0.02, 0.20, 0.40, 0.60, 0.75, 0.87)
) +
ggtitle("") +
theme(
panel.spacing.x = unit(0, "lines"), axis.title.x = element_blank(),
axis.text = element_blank(), axis.ticks = element_blank(),
axis.title.y = element_blank(), plot.title = element_text(
hjust = 0.5,
size = 18, face = "bold"
), strip.background = element_blank(),
strip.text = element_text(size = 14, color = "black", face = "bold"),
legend.text = element_text(size = 14, face = "bold"),
legend.title = element_text(hjust = 0.1, size = 16, face = "bold"),
panel.background = element_blank()
) +
guides(fill = guide_colourbar(
title = "Relative yield", title.hjust = 0.5,
barheight = 15, barwidth = 2
))

Related

Editing legend in ggplot2 - R

I'm learning to use ggplot to make graphs for my research and I'm having some trouble setting legends for them.
Initially I thought about just using the aes() function inside geom_point and geom_line to get the aesthetics I'm looking for. However, I realized the legends weren't being generated by doing it this way. Code and exemple below.
#Stablish the variables as vectors
MexxJan_hydrogen <- c(0, 1.38, 3.19, 8.30)
MexyJan_hydrogen <- c(0, 1.25, 2.78, 6.23)
MexzJan_hydrogen <- c(0, 2.46, 5.68, 12.18)
MexwJan_hydrogen <- c(0, 7.56, 9.20, 10.19)
time_hydrogen <- c(0, 60, 120, 180)
#Create the data frame
hydrogen_data <- data.frame(time_hydrogen, MexxJan_hydrogen, MexyJan_hydrogen, MexzJan_hydrogen, MexwJan_hydrogen)
view(hydrogen_data)
#Code the plot
hydrogen_plot <- ggplot(data = hydrogen_data) +
geom_line(aes(x = time_hydrogen, y = MexxJan_hydrogen), color = "palegreen3", lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexyJan_hydrogen), color = "tan1", lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexzJan_hydrogen), color = "tomato2", lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexwJan_hydrogen), color = "cadetblue", lwd = 1) +
geom_point(aes(x = time_hydrogen, y = MexxJan_hydrogen), color = "palegreen3", shape = 15, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexyJan_hydrogen), color = "tan1", shape = 16, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexzJan_hydrogen), color = "tomato2", shape = 17, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexwJan_hydrogen), color = "cadetblue", shape = 18, size = 5) +
theme_bw() +
theme(axis.text = element_text(family = "Arial", size = 15, color = "black"),
axis.title.x = element_text(family = "Arial", size = 16, margin = margin(t = 15)),
axis.title.y = element_text(family = "Arial", size = 16, margin = margin(r = 15)),axis.line = element_line(color = "black"),
plot.background = element_rect(fill = "transparent", color = NA),
panel.border = element_rect(color = "black"),
panel.background = element_rect(fill = "transparent"),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.ticks.length = unit(0.20, units = "cm"),
legend.background = element_rect(fill = "transparent"),
legend.key = element_rect(fill = "transparent", colour = NA),
legend.position = "top",
legend.key.width = unit(0, unit = "cm"),
legend.key.height = unit(0, unit = "cm"),
legend.title = element_blank(),
legend.text = element_text(size = 13.5),
legend.spacing.x = unit(0.1, "cm"),
legend.text.align = unit(0.05, unit = "cm")) +
labs(x = "Time (min)", y = "Gas Evolution (µmol.g"^-1~")") +
coord_cartesian(ylim = c(0,15), xlim = c(0,180)) +
scale_y_continuous(expand = expansion(mult = c(0.02, 0.02)),
n.breaks = 5) +
scale_x_continuous(expand = expansion(mult = c(0.02, 0.02)),
breaks = c(0, 60, 120, 180))
I then found that I could use the function scale_colors_manual to get the desired colors and show the legend. Also, using scale_colors_manual I managed to change the legend text to a shorter option. Code and exemple below.
#Stablish the variables as vectors
MexxJan_hydrogen <- c(0, 1.38, 3.19, 8.30)
MexyJan_hydrogen <- c(0, 1.25, 2.78, 6.23)
MexzJan_hydrogen <- c(0, 2.46, 5.68, 12.18)
MexwJan_hydrogen <- c(0, 7.56, 9.20, 10.19)
time_hydrogen <- c(0, 60, 120, 180)
#Create the data frame
hydrogen_data <- data.frame(time_hydrogen, MexxJan_hydrogen, MexyJan_hydrogen, MexzJan_hydrogen, MexwJan_hydrogen)
view(hydrogen_data)
hydrogen_plot <- ggplot(data = hydrogen_data) +
geom_line(aes(x = time_hydrogen, y = MexxJan_hydrogen, color = "MexxJan_hydrogen"), lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexyJan_hydrogen, color = "MexyJan_hydrogen"), lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexzJan_hydrogen, color = "MexzJan_hydrogen"), lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexwJan_hydrogen, color = "MexwJan_hydrogen"), lwd = 1) +
geom_point(aes(x = time_hydrogen, y = MexxJan_hydrogen, color = "MexxJan_hydrogen"), shape = 15, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexyJan_hydrogen, color = "MexyJan_hydrogen"), shape = 16, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexzJan_hydrogen, color = "MexzJan_hydrogen"), shape = 17, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexwJan_hydrogen, color = "MexwJan_hydrogen"), shape = 18, size = 5) +
theme_bw() +
theme(axis.text = element_text(family = "Arial", size = 15, color = "black"),
axis.title.x = element_text(family = "Arial", size = 16, margin = margin(t = 15)),
axis.title.y = element_text(family = "Arial", size = 16, margin = margin(r = 15)),axis.line = element_line(color = "black"),
plot.background = element_rect(fill = "transparent", color = NA),
panel.border = element_rect(color = "black"),
panel.background = element_rect(fill = "transparent"),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.ticks.length = unit(0.20, units = "cm"),
legend.background = element_rect(fill = "transparent"),
legend.key = element_rect(fill = "transparent", colour = NA),
legend.position = "top",
legend.key.width = unit(0, unit = "cm"),
legend.key.height = unit(0, unit = "cm"),
legend.title = element_blank(),
legend.text = element_text(size = 13.5),
legend.spacing.x = unit(0.1, "cm"),
legend.text.align = unit(0.05, unit = "cm")) +
labs(x = "Time (min)", y = "Gas Evolution (µmol.g"^-1~")") +
coord_cartesian(ylim = c(0,15), xlim = c(0,180)) + #Limit the size of the plot
scale_y_continuous(expand = expansion(mult = c(0.02, 0.02)),
n.breaks = 5) +
scale_x_continuous(expand = expansion(mult = c(0.02, 0.02)),
breaks = c(0, 60, 120, 180)) +
scale_color_manual(labels = c("15Me-NT", "15Me-nNT", "15Me-NNT", "15Me-nnt"),
values = c("MexxJan_hydrogen" = "palegreen3", "MexyJan_hydrogen" = "tan1", "MexzJan_hydrogen" = "cadetblue", "MexwJan_hydrogen" = "tomato2"))
In this case, I got the colors and the legend. However, as you can see in the image, the legend keys look like a bunch of geometric forms stacked. I couldn't find a way to solve this. Tried using scale_shape_manual but I couldn't get the code right.
May you help me getting this plot some beautiful aesthetics? hehehe
Thank you. Stay safe.
To fix your issue you have to move shape inside aes similar to what you have done for color and afterwards set your shapes via scale_shape_manual. However, you could simplify your approach considerably by first reshaping your data to long or tidy data format. Doing so allows to add your lines and points which just one geom_point and geom_line:
library(tidyr)
library(ggplot2)
hydrogen_data_long <- hydrogen_data %>%
tidyr::pivot_longer(-time_hydrogen, names_to = "hydrogren")
ggplot(hydrogen_data_long, aes(x = time_hydrogen, y = value, color = hydrogren)) +
geom_line(lwd = 1) +
geom_point(aes(shape = hydrogren), size = 5) +
scale_shape_manual(
labels = c("15Me-NT", "15Me-nNT", "15Me-NNT", "15Me-nnt"),
values = c(
"MexxJan_hydrogen" = 15, "MexyJan_hydrogen" = 16,
"MexzJan_hydrogen" = 17, "MexwJan_hydrogen" = 18
)
) +
scale_color_manual(
labels = c("15Me-NT", "15Me-nNT", "15Me-NNT", "15Me-nnt"),
values = c(
"MexxJan_hydrogen" = "palegreen3", "MexyJan_hydrogen" = "tan1",
"MexzJan_hydrogen" = "cadetblue", "MexwJan_hydrogen" = "tomato2"
)
) +
theme_bw() +
theme(
axis.text = element_text(family = "Arial", size = 15, color = "black"),
axis.title.x = element_text(family = "Arial", size = 16, margin = margin(t = 15)),
axis.title.y = element_text(family = "Arial", size = 16, margin = margin(r = 15)),
axis.line = element_line(color = "black"),
plot.background = element_rect(fill = "transparent", color = NA),
panel.border = element_rect(color = "black"),
panel.background = element_rect(fill = "transparent"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks.length = unit(0.20, units = "cm"),
legend.background = element_rect(fill = "transparent"),
legend.key = element_rect(fill = "transparent", colour = NA),
legend.position = "top",
legend.key.width = unit(0, unit = "cm"),
legend.key.height = unit(0, unit = "cm"),
legend.title = element_blank(),
legend.text = element_text(size = 13.5),
legend.spacing.x = unit(0.1, "cm"),
legend.text.align = unit(0.05, unit = "cm")
) +
labs(x = "Time (min)", y = "Gas Evolution (µmol.g"^-1 ~ ")") +
coord_cartesian(ylim = c(0, 15), xlim = c(0, 180)) + # Limit the size of the plot
scale_y_continuous(
expand = expansion(mult = c(0.02, 0.02)),
n.breaks = 5
) +
scale_x_continuous(
expand = expansion(mult = c(0.02, 0.02)),
breaks = c(0, 60, 120, 180)
)
You are making life harder for yourself by passing your data frame in the wrong format. If you pivot to long format, you only need a single geom_line and geom_point. It's also far easier to map your colors and shapes, which will automatically appear in the legend.
Also, try to choose a default theme that's closer to the look you want to achieve to cut down on the number of tweaks you have to make via theme. One of the key things you'll learn in R, as in other languages, is that cutting down code to a minimum makes it easier to change or debug your code later on.
library(tidyverse)
hydrogen_data %>%
pivot_longer(-time_hydrogen) %>%
ggplot(aes(time_hydrogen, value, color = name, shape = name)) +
geom_line(lwd = 1) +
geom_point(size = 5) +
scale_color_manual(values = c("tomato2", "palegreen", "tan1", "cadetblue"),
labels = paste0("15Me-", c("NT", "nNT", "NNT", "nnt"))) +
scale_shape_manual(values = c(18, 15, 16, 17),
labels = paste0("15Me-", c("NT", "nNT", "NNT", "nnt"))) +
scale_y_continuous(expression(Gas~Evolution~(µmol.g^-1)),
expand = expansion(mult = c(0.02, 0.02)), n.breaks = 5) +
scale_x_continuous("Time (min)", expand = expansion(mult = c(0.02, 0.02)),
breaks = c(0, 60, 120, 180)) +
theme_classic(base_size = 16) +
theme(axis.text = element_text(family = "Arial", size = 15, color = "black"),
plot.background = element_blank(),
panel.border = element_rect(color = "black", fill = NA),
panel.background = element_blank(),
axis.ticks.length = unit(0.20, units = "cm"),
legend.background = element_blank(),
legend.position = "top",
legend.title = element_blank()) +
coord_cartesian(ylim = c(0, 15), xlim = c(0, 180))

How to make a dual y-axis line plot with a polynomial function in ggplot2?

I need help with the modification of a plot with y-axis. In Excel I don't have trouble, but the hard part is in R. Besides, I uploaded an example of the final plot in excel.
It is not relevant the data you used.
I will appreciate your help.
Required double y-axis with polynomial function plot:
#Make lm model
Model<- lm(V~ T,data=data1)
summary(Model)
anova(Model)
HSD.test(Model, 'T', group = T, MSerror, alpha = 0.05, console = T)
#Make eq
eq <- function(data1){
m<- lm(V~T);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
}
#Make plot
ggplot(data, aes(x=Time, y=mean))+
geom_line()+
geom_smooth(method=loess)+
stat_regline_equation(label.y = 4.0e-06, aes(label=..eq.label..))+
stat_regline_equation(label.y = 3.8e-06, aes(label=..rr.label..))+
geom_pointrange(aes(ymin=mean-se, ymax=mean+se))+
theme(
line = element_line(colour = "black", size = 1, linetype = 1, lineend = "butt"),
rect = element_rect(fill = "white", colour = "black", size = 1, linetype = 1),
aspect.ratio = 1,
plot.background = element_rect(fill = "white"),
plot.margin = margin(1, 1, 1, 1, "cm"),
axis.text = element_text(size = rel(2.5), colour = "#000000", margin = 1),
strip.text = element_text(size = rel(0.8)),
axis.line = element_blank(),
axis.text.x = element_text(vjust = 0.2, angle=0),
axis.text.y = element_text(hjust = 1),
axis.ticks = element_line(colour = "#000000", size = 1.2),
axis.title.x = element_text(size = 30, vjust=0.5),
axis.title.y = element_text(size = 30, angle = 90),
axis.ticks.length = unit(0.1, "cm"),
legend.background = element_rect(colour = NA),
legend.margin = unit(0.15, "cm"),
legend.key = element_rect(fill = "grey95", colour = "white"),
legend.key.size = unit(1.2, "lines"),
legend.key.height = NULL,
legend.key.width = NULL,
legend.text = element_text(size = rel(2.0)),
legend.text.align = NULL,
legend.title = element_text(size = rel(2.0), face = "bold", hjust = 0),
legend.title.align = NULL,
legend.position = "right",
legend.direction = NULL,
legend.justification = "right",
legend.box = NULL,
panel.background = element_rect(fill = "#ffffff", colour = "#000000",
size = 2, linetype = "solid"),
panel.border = element_rect(colour = "black", fill=NA, size=2),
)+
ylab(expression(Volume~(m^3))) + xlab(expression(Time~(min)))

geom_point not showing up on ggplot with geom_sf of rivers

I am trying to build a map that contains a few points overlayed onto rivers. I am using code adapted from https://milospopovic.net/map-rivers-with-sf-and-ggplot2-in-r/, but I downloaded the North America map and substituted
st_polygon(list(cbind(
c(-84.9, -84.9, -84.0, -84.0, -84.9),
c(34.4, 35.05, 35.05, 34.4, 34.4)
))),
crs = crsLONGLAT)
to create my bounding box.
test.point <- data.frame("x"= -84.73405, "y"= 35.00988)
p <-
ggplot()+
geom_point(data= test.point, aes(x=x, y=y), color= "black", fill= "black") +
geom_sf(data=na_riv, aes(color=factor(ORD_FLOW), size=width)) +
coord_sf(crs = 4087,
xlim = c(bbox["xmin"], bbox["xmax"]),
ylim = c(bbox["ymin"], bbox["ymax"])) +
labs(x= "", subtitle="",
title="Rivers of the Southeast",
caption="©2022\nSource: ©World Wildlife Fund, Inc. (2006-2013)\n HydroSHEDS database http://www.hydrosheds.org") +
scale_color_manual(
name = "",
values = c('#081f6b', '#08306b', '#08519c', '#2171b5', '#4292c6', '#6baed6', '#9ecae1', '#c6dbef', '#deebf7')) +
scale_size(range=c(0, .3)) +
scale_alpha_manual(values=c("2"= 1, "3" = 1, "4" = 1, "5" = .7, "6" = .6, "7" = .4, "8" = .3, "9" = .2, "10" = .1)) +
theme_bw() +
theme(text = element_text(family = "georg"),
panel.background = element_blank(),
legend.background = element_blank(),
legend.position = "none",
panel.border = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
plot.title = element_text(size=40, color="#2171b5", hjust=0.5, vjust=0),
plot.subtitle = element_text(size=14, color="#ac63a0", hjust=0.5, vjust=0),
plot.caption = element_text(size=10, color="grey60", hjust=0.5, vjust=10),
legend.text = element_text(size=9, color="grey20"),
legend.title = element_text(size=10, color="grey20"),
strip.text = element_text(size=12),
plot.margin = unit(c(t=1, r=0, b=-1, l=-1),"lines"))
p
The above code yields a pretty map of all of the rivers but the point doesn't show up. :(
Here is one way to get around this. Basically you can convert the points you want to highlight a a simple feature geometry:
test.point <- data.frame(x = c(-84.73405, -84.6), y = c(35.00988, 34.6))
new_test.point <- st_sfc(st_multipoint(as.matrix(test.point)), crs = crsLONGLAT)
Then, I just filtered the data to have only the rivers present in the area of interested:
nariv = nariv %>% mutate(inter = as.integer(st_intersects(geometry, bbox)))
nariv_filt = nariv %>% filter(!is.na(inter))
And create the plot:
ggplot() +
geom_sf(data = nariv_filt, aes(color = factor(ORD_FLOW), size = width, alpha = width)) +
geom_sf(data = new_test.point, color="red", size=5)+
coord_sf(crs = prj, xlim = c(bb["xmin"], bb["xmax"]),ylim = c(bb["ymin"], bb["ymax"])) +
geom_point(data = test.point, aes(x=x, y=y), color="red", size=5)+
labs(y = "", subtitle = "", x = "", title = "Rivers of North and Central America") +
scale_color_manual(name = "",
values = c(
"#08306b", "#1c4680", "#305d94", "#4574a7",
"#5d8cb9", "#77a4cb", "#deebf7", "#deebf7", "#deebf7"
), drop = F) +
scale_alpha(range = c(0.3, 0.8)) +
scale_size(range = c(0, 3)) +
theme_minimal() +
theme(
text = element_text(family = "Montserrat"),
panel.background = element_blank(),
legend.background = element_blank(),
legend.position = "none",
panel.border = element_blank(),
#panel.grid.minor = element_blank(),
#panel.grid.major = element_blank(),
#plot.title = element_text(size = 100, color = "#2171b5", hjust = 0.5, vjust = -22),
#plot.subtitle = element_text(size = 14, color = "#ac63a0", hjust = 0.5, vjust = 0),
#plot.caption = element_text(size = 40, color = "grey60", hjust = 0.5, vjust = 120),
#axis.title.x = element_text(size = 10, color = "grey20", hjust = 0.5, vjust = -6),
legend.text = element_text(size = 9, color = "grey20"),
legend.title = element_text(size = 10, color = "grey20"),
strip.text = element_text(size = 12),
#plot.margin = unit(c(t = -2.5, r = -10, b = -10, l = -10), "lines"),
axis.title.y = element_blank(),
axis.ticks = element_blank(),
#axis.text.x = element_blank(),
#axis.text.y = element_blank()
)

Ajust variable order and color in forest plot (ggplot2)

I have adapted the solution to align forest plot and a table from this post:
how to align table with forest plot (ggplot2)
Here is my code:
library(dplyr, warn = FALSE)
library(ggplot2)
library(patchwork)
tester <- data.frame(
treatmentgroup = c("Education Continuous", "0", "1-4",
"5-8", ">8"),
or = c(0.914, 0.961, 0.709, 0.523, 0.457),
low_ci = c(0.894, 0.793, 0.577, 0.389, 0.339),
up_ci = c(0.935, 1.166, 0.871, 0.708, 0.616),
OR_ci = c(
"0.914 (0.894; 0.935)", "0.961 (0.793; 1.166)", "0.709 (0.577; 0.871)",
"0.523 (0.389; 0.708)", "0.457 (0.339; 0.616)"),
ci = c(
"0.894; 0.935",
"0.793; 1.166",
"0.577; 0.871",
"0.389; 0.708",
"0.339; 0.616"),
no = c(1, 2, 3, 4, 5)
)
forest <- ggplot(
data = tester,
aes(x = treatmentgroup, y = or, ymin = low_ci, ymax = up_ci)) +
geom_pointrange(aes(col = treatmentgroup)) +
geom_hline(yintercept = 1, colour = "black") +
xlab("") +
ylab("OR (95% CI)") +
geom_errorbar(aes(ymin = low_ci, ymax = up_ci, col = treatmentgroup), width = 0, cex = 1) +
theme_classic() +
theme(
panel.background = element_blank(), strip.background = element_rect(colour = NA, fill = NA),
strip.text.y = element_text(face = "bold", size = 12),
panel.grid.major.y = element_line(colour = col_grid, size = 0.5),
strip.text = element_text(face = "bold"),
panel.border = element_rect(fill = NA, color = "black"),
legend.position = "none",
axis.text = element_text(face = "bold"),
axis.title = element_text(face = "bold"),
plot.title = element_text(face = "bold", hjust = 0.5, size = 13)
) +
coord_flip()
dat_table <- tester %>%
select(treatmentgroup, OR_ci) %>%
tidyr::pivot_longer(c(OR_ci), names_to = "stat") %>%
mutate(stat = factor(stat, levels = "OR_ci"))
table_base <- ggplot(dat_table, aes(stat, treatmentgroup, label = value)) +
geom_text(size = 3) +
scale_x_discrete(position = "top", labels = "OR (95% CI)") +
labs(y = NULL, x = NULL) +
theme_classic() +
theme(
strip.background = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_blank(),
axis.line = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(size = 12),
axis.ticks = element_blank(),
axis.title = element_text(face = "bold"),
)
forest + table_base + plot_layout(widths = c(10, 4))
However, my graph ends up with the categories out of order. How can I adjust the order to this one: Education Continuous, 0, 1-4, 5-8, and >8?
I tried factor(tester$treatmentgroup) but it did not work.
Also, how can I make all the categories the same color (black, for example) instead of one each color? I tried eliminating the line geom_pointrange(aes(col = treatmentgroup)) + but it does not work.
You're right that you can convert treatmentgroup to a factor, you just need to specify the levels. Try running this code before you generate your plots with ggplot().
tester <- tester %>%
mutate(treatmentgroup = factor(treatmentgroup,
levels = c(">8", "5-8", "1-4", "0", "Education Continuous")))

Make R Plot Axes the Same for Multi-Plot Figure

I have 3 multi-plot figures I'm making for a manuscript and R is shrinking the first plot in the 2 figures with 3 paneled plots. They have different axes and scales so I couldn't use a facet function, but ggarrange() does what I need. Is there a way to make the size of the actual graphs identical?enter image description here
Plot 1 axes smaller
Here's the script generating them:
library(ggplot2)
library(ggpubr)
library(ggpmisc)
library(ggrepel)
library(tidyverse)
summary_bp <- read.table("1500bp_amas_summary.txt", header=TRUE)
alignment_length <- summary_bp$Alignment_length
no_inf_sites <- summary_bp$Parsimony_informative_sites
Length_Site_Reg <- ggplot(summary_bp, aes(x=alignment_length, y=no_inf_sites)) +
geom_point(shape = 1, size = 1) +
geom_smooth(method = lm, size = 0.7) +
stat_regline_equation(label.x = 3000, label.y = 3500, geom = "text", aes(label= ..rr.label..), size = 2) +
stat_cor(method = "pearson", label.x = 3000, label.y = 3100,aes(label = ..p.label..), size = 2) +
coord_cartesian(xlim = c(1500, 15000), ylim = c(0,4000)) +
scale_x_continuous(breaks = seq(1500, 15000, by=1500)) +
scale_y_continuous(breaks = seq(0, 4000, by=500)) +
labs( x = "Alignment Lengths", y = "Number of Parsimony \n Informative Sites") +
theme(aspect.ratio = 1, axis.text.x = element_text(angle=45, hjust = 1),
axis.line = element_line(color = "black"), panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text = element_text(size = 7),
axis.title.x = element_text(size = 9, face = "bold"), axis.title.y = element_text(size = 8, face = "bold"))
Length_Site_Reg
#Fig. 3b) GC hist
summary_all <- read.table("summary_trim.txt", header=TRUE, sep = ",")
GC_hist <- ggplot(data = summary_all, aes(x=GC_content)) +
geom_histogram(binwidth = 0.025, fill = "white", color = "black") +
xlim(0.3,0.725) +
coord_cartesian( ylim = c(0,1050)) +
labs(x = "GC Content", y = "Number of Orthologs") +
theme(aspect.ratio = 1, panel.background = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), legend.position = c(0.75, 0.65),
axis.line = element_line(color = "black"), axis.text = element_text(size = 8),
axis.title = element_text(size = 9, face = "bold"), legend.key.size = unit(0.4, 'cm'),
legend.key.height = unit(0.4, 'cm'),
legend.key.width = unit(0.4, 'cm'),
legend.title = element_text(size=6),
legend.text = element_text(size=6)) +
geom_vline(aes(xintercept=mean(GC_content), color="mean"),
linetype="solid", size=0.5, show.legend = FALSE)
GC_hist
# Fig. 3c) K2P Divergence Hist
#trimmed_k2 <- file.choose()
trimmed_k2_data <- read.table("trimmed_alignment_k2.csv", header=TRUE, sep = ",")
trimmed_k2_data
trimmed_k2_data_hist <- ggplot(data = trimmed_k2_data, aes(x=distance)) +
geom_histogram(binwidth = 0.025, fill = "white", color = "black") +
coord_cartesian( ylim = c(0,1200) ) + scale_y_continuous(breaks = seq(0,1200,200)) +
labs(x = "K2P Distance", y = "Number of Orthologs", size= 3) +
theme(aspect.ratio = 1, panel.background = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(color = "black"),
axis.text = element_text(size = 8),
axis.title = element_text(size = 9, face = "bold")) +
geom_vline(aes(xintercept=mean(distance)), linetype="solid", colour="red", size=0.5, show.legend = FALSE)
trimmed_k2_data_hist
Fig3_plots <-ggarrange(Length_Site_Reg, GC_hist, trimmed_k2_data_hist, ncol = 3, widths = 1, heights = 1)
Fig3_plots

Resources