Aligning two ggplots with grid.arrange - r

I would like to have two ggplots aligned and the same x axis length. Somehow it does not work. Here is my code:
#5cm_Four Treatments different color
d1<-ggplot(MyDataMoistWinkler[550:10000,], aes(x=betterDate)) +
geom_line(aes(y=VerticalTillHigh5cm, color="Vertical Till High Disturbance 5cm"))+
geom_line(aes(y=VerticalTillLow5cm, color="Vertical Till Low Disturbance 5cm"))+
geom_line(aes(y=StripST5cm, color="Strip Till in row"))+
geom_line(aes(y=StripNT5cm, color="Strip Till between row"))+
geom_line(aes(y=Disc5cm, color="Double Disc"))+
xlab("Date")+
ylab("Volumetric Water Content [m3/m3]")+
scale_y_continuous(limits = c(0, NA))+
theme(text = element_text(size = 11, colour = "black"))+
theme(legend.title=element_blank())+
#theme(panel.background = element_blank(), panel.grid = element_line( size=.5, colour="black" ) )+
theme(axis.text = element_text(size = 15, colour = "grey"))+# changes axis labels
theme(axis.title = element_text(size = 15))+ # change axis titles
theme(text = element_text(size = 15, colour = "black"))+ # this will change all text size # (except geom_text)
theme(strip.text.x = element_text(size = 15, colour = "black", angle =NULL))+
ggtitle("Moisture in 5cm, in Winkler MB")
d2<-ggplot(MyDataMoistWinkler[550:10000,], aes(x=betterDate, y=AccumulatedRainfall)) +
geom_line(aes(y=AccumulatedRainfall, color="Accumulated Rainfall"))+
xlab("Date ")+
ylab("Accumulated Rainfall [mm]")+
scale_y_continuous(limits = c(0, NA))+
theme(text = element_text(size = 11, colour = "black"))+
theme(legend.title=element_blank())+
#theme(panel.background = element_blank(), panel.grid = element_line( size=.5, colour="black" ) )+
theme(axis.text = element_text(size = 15, colour = "grey"))+# changes axis labels
theme(axis.title = element_text(size = 15))+ # change axis titles
theme(text = element_text(size = 15, colour = "black"))+ # this will change all text size # (except geom_text)
theme(strip.text.x = element_text(size = 15, colour = "black", angle =NULL))+
ggtitle("Precipitation in mm, in Winkler MB")
1st Option: If you want to arrange them next to each other
require(gridExtra)
grid.arrange(d1, d2, ncol=1)

library(grid)
grid.draw(rbind(ggplotGrob(d1), ggplotGrob(d2)))
might work

Related

Creating Dual Axis plot (bar and line)

I want to create a dual axis plot in ggplot R with a dual bar and line plot, like this one created in excel.
The y axis scales are different.
my data is as follows;
I've created a bar plot and line plot. But unsure on how to put them together (I've tried man various ways and they don't seem to work).
Here is my code for the bar plot.
inf_conc <- ggplot(data=data, aes(x=Day, y=inf)) +
geom_bar(stat="identity", width=0.4, color="red3", fill="red3") +
ggtitle("Influent Microplastic Concentration \n and Flow Rate") +
# \n splits long titles into multiple lines
xlab("Day") +
ylab("Microplastic Concentration (MPs/L)") +
scale_y_continuous(limits =c(0, 50), breaks = seq(0, 50, 5))
inf_conc + theme(axis.text = element_text(size = 20, colour = "black"),
plot.title = element_text(size =25, hjust = 0.5,
face = "bold"), axis.title = element_text(size = 20,
face = "bold", margin = 5))
inf_conc + theme(axis.text = element_text(size = 20, colour = "black"),
plot.title = element_text (size =25, hjust = 0.5, face = "bold"),
axis.title = element_text(size = 20, face = "bold", margin = 20))
and here is the code for the line plot:
inf_flow <- ggplot(data=data, aes(x=Day, y=flow, group = 1)) +
geom_line(stat = "identity", colour ="blue4") +
geom_point(colour ="blue4") +
ylab("Inlet flow L/s")+
xlab("Day")+
scale_y_continuous(limits=c(0,800), breaks = seq(0, 800, 100))
inf_flow + theme(axis.text = element_text(size = 20, colour = "black"),
plot.title = element_text (size =25, hjust = 0.5, face = "bold"),
axis.title = element_text(size = 20, face = "bold", margin = 5))
inf_flow + theme(axis.text = element_text(size = 20,
colour = "black"), plot.title = element_text (size =25, hjust = 0.5,
face = "bold"), axis.title = element_text(size = 20, face = "bold",
margin = 20))
Can anyone help with how I can get these onto one dual axis graph please.
GGplot doesn't make it especially easy, but you can do it:
library(ggplot2)
my_dat <- data.frame(
Day = paste("Day",rep(1:3, each=3), rep(c("(AM)", "(Midday)", "(PM)"), 3), sep= " "),
day_num = 1:9,
inf = seq(from = 13,to = 45, length=9),
flow = runif(9, 580, 740)
)
ggplot() +
geom_bar(data=my_dat, aes(x=day_num, y=inf, fill = "Influent Concentration"), stat="identity", width=.6) +
geom_line(data=my_dat, aes(x=day_num, y=flow*(50/800), colour="FLow Rate. L/s")) +
scale_fill_manual(values="red") +
scale_colour_manual(values="blue") +
scale_x_continuous(breaks=1:9, labels=my_dat$Day) +
scale_y_continuous(sec.axis = sec_axis(trans = ~.x*800/50, name = "Flow Rate L/S"), limits = c(0,50), name = "Influent. MPs/L") +
labs(fill="", colour="", x="") +
theme(legend.position="bottom",
axis.text.x = element_text(angle=45, hjust=1))
Created on 2023-01-17 by the reprex package (v2.0.1)
The main things you have to do are to
Transform the second-axis series to have the same range(ish) as the first-series axis. In your case, the excel graph had the second y-axis going from 0-800 and the first y-axis going from 0-50, so the transformation is simple, you multiply the second series values by 50/800.
In the scale_y_continuou() function there is an argument sec.axis which allows you to plot a second axis on the right-hand side of the plot. Here, you need to specify the trans argument to transform the values you're plotting back into the original values. That's what trans = ~.x*800/50 does.
EDIT: Modifying OP's code
I modified your code as much as I can without actually having the data. The picture of the data that you provided does not give enough information about the data, if you use dput(data) and post the results, I could likely help more. For now, try this:
inf_plot <- ggplot(data=data, aes(x=Day))+
geom_bar(aes(y=inf, fill="Influent conc"), stat = "identity", width=0.4)+
geom_line(aes(y=flow*(50/800), colour="flow rate"), size = 1.4, group=1)+
ggtitle("Influent Microplastic Concentration \n and Influent Flow Rate")+
xlab("\n\nDay") +
ylab("Microplastic Concentration (MPs/L)\n\n")+
scale_fill_manual(values="red4") +
scale_colour_manual(values="blue4") +
scale_y_continuous(sec.axis = sec_axis(~.*800/50, name = "Inlet flow rate (L/s)\n\n"), limits = c(0,50))
inf_plot + theme(axis.text = element_text( size = 20, colour = "black"),
plot.title = element_text (size =25, hjust = 0.5, vjust = 5, face = "bold"),
axis.title = element_text (size = 20, face = "bold"),
plot.margin =unit(c(1.5, 1.5, 1.5, 1.5), "cm"),
legend.position = "bottom")
The answer was a great help in how to transform my axis.
Initially produced the graph a slightly different way, but incorporated the same transformation of axis.
However, I can't seem to get the legend to appear at the bottom of the graph with the following code.
inf_plot <- ggplot(data=data, aes(x=Day))+
geom_bar(aes(y=inf, fill="Influent conc"), stat = "identity", width=0.4,
colour="red4", fill = "red4")+
ggtitle("Influent Microplastic Concentration \n and Influent Flow Rate")+
xlab("\n\nDay") +
ylab("Microplastic Concentration (MPs/L)\n\n")+
geom_line(aes(y=flow*(50/800), colour="flow rate"), size = 1.4, colour ="blue4", group = 1)+
scale_fill_manual(values="red4") +
scale_colour_manual(values="blue4") +
scale_y_continuous(sec.axis = sec_axis(~.*800/50, name = "Inlet flow rate (L/s)\n\n"), limits = c(0,50))
inf_plot + theme(axis.text = element_text( size = 20, colour = "black"),
plot.title = element_text (size =25, hjust = 0.5, vjust = 5, face = "bold"),
axis.title = element_text (size = 20, face = "bold"),
plot.margin =unit(c(1.5, 1.5, 1.5, 1.5), "cm"),
legend.position = "bottom")
enter image description here

ggplot2 increase font size of output labels

I am working with ggplot2 to create plots and I want to increase the size of the labels from the output, so not the labels added manually.
I tried to use cex put this works only partially as it only increases the count size in the plot but not the x or y labels
ggplot(dat, aes(x = Gender, fill = gen))+
geom_bar(position = "dodge")+
scale_fill_manual(values = c("#40E0D0","#DE3163"))+
labs(y="All", fill ="Gender:")+
scale_y_continuous(breaks = seq(0,550,50))+
ggtitle("Gender")+
theme(axis.title.x = element_text(size =20, face = "bold"))+
theme(axis.title.y = element_text(size = 20, face = "bold", angle = 90))+
theme(plot.title = element_text(size = 30, face="bold"), legend.position = "bottom")+
geom_text(aes(label=stat(count), cex = 6), stat = "count",
position=position_dodge(width = 1),vjust= -0.2, cex = 6)+
theme(legend.title = element_text(size = 20))+
theme(legend.text = element_text(size = 20))
``

Plot title in R not changing / being edited even with theme plot.title

I'm trying to edit my plot title but no matter what I try for whatever reason it won't actually change. Can someone please help me figure out what's going on? I've also tried adding a different theme before my other theme but that just screws everything else up. I'd appreciate any help!
I've attached an image of my code and my plot below. As you will see I've set
theme(plot.title = element_text(face = "bold.italic", colour="black",
size = 12, hjust = 0.5)
but the plot is not reflecting any of those edits.
Code
Never mind I was able to figure it out by introducing the black and white theme and then editing the theme. See code below:
G1B2stodenplot2 <- ggplot(G1B2stodenplot, aes(x=Drought, y=Average_stomatal_density_of_FOV_area, colour=Locality, shape=Locality, group=Locality, shape=Locality)) +
geom_errorbar(aes(ymin=Average_stomatal_density_of_FOV_area-se, ymax=Average_stomatal_density_of_FOV_area+se), colour="black", width=.1, position=pd) +
geom_line(aes(group=Locality, linetype=Locality), show.legend=FALSE, position=pd) + #makes the different lines connecting dots, adds the lines, removes geom_line legend
geom_point(aes(group=Locality, shape=Locality), size=4, fill="white", position=pd) +
#geom_point(position=pd, size=4, shape=21, fill="white") + #21 is filled circle
scale_colour_manual(name = "Populations",
labels = c("Anderson Dam", "Northern Swanton", "Southern Swanton"),
values = c("orange", "blue", "brown4")) +
scale_shape_manual(name = "Populations",
labels = c("Anderson Dam", "Northern Swanton", "Southern Swanton"),
values = c(17, 16, 15)) + #shape numbers
#labs(title="Evolution & Plasticity in Stomatal Density of"~italic("Collinsia multicolor"), x="Years", y="# / mm^2")+
ggtitle("Evolution in Stomatal Density of"~italic("Collinsia multicolor"))+
xlab("Years") +
ylab("# / mm^2") +
ylim(25, 40)+ #changes y-axis limits
xlim("Predrought", "Postdrought")+
theme_bw()+
theme(plot.title = element_text(colour = "black", size = 14, face = "bold", hjust = 0.5),
panel.background = element_rect(fill="white"), # Set plot background to white
panel.grid.major = element_blank(), #remove grid lines
panel.grid.minor = element_blank(), #remove gride lines
#panel.border = element_blank(), #remove plot border
legend.key = element_rect(fill = "white"), # Set legend item backgrounds to white
legend.box.background = element_rect(colour = "black"), #set legend border & color black
legend.title = element_text(hjust = 0.5, color = "black", size = 10, face = "bold"),
#axis.line.x = element_line(colour = "black", size = 1), # Add line to x axis
#axis.line.y = element_line(colour = "black", size = 1), # Add line to y axis
axis.text.x = element_text(face="bold", colour="black", size=10),
axis.text.y = element_text(face="bold", colour="black", size=10),
axis.title.x = element_text(colour = "black", size = 12, face = "bold"),
axis.title.y = element_text(colour = "black", size = 12, face = "bold"),
axis.ticks.length=unit(-0.25, "cm"), #changes tick mark length
axis.ticks.margin=unit(0.5, "cm") #changes tick mark in or out of plot
)
G1B2stodenplot2

How to make y-axis labels overlap for ggplot figures in R

The y-axis for both figures below are the same (i.e., mpg) and have the same scale. I would like the figure on the left to overlap the y-axis of the figure on the right such that you can only see the tick marks of the y-axis for the figure on the right.
The code below makes both figures and aligns them however you can still see the y-axis labels for the figure on the right.
library(ggplot2)
library(ggpubr)
p1 <- ggplot(mtcars) +
geom_point(aes(x=disp,y=mpg)) +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 16, color = "black"),
axis.text.y = element_text(size = 16, color = "black"))
p2 <- ggplot(mtcars) +
geom_point(aes(x=hp,y=mpg)) +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 16, color = "black"),
axis.text.y = element_text(size = 16, color = "black"))
ggarrange(p1,p2,nrow = 1)
The ideal output would look like this:
Just add axis.text.y = element_blank(), axis.title.y = element_blank()) to your code:
library(ggplot2)
library(ggpubr)
p1 <- ggplot(mtcars) +
geom_point(aes(x=disp,y=mpg)) +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 16, color = "black"),
axis.text.y = element_text(size = 16, color = "black"))
p2 <- ggplot(mtcars) +
geom_point(aes(x=hp,y=mpg)) +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 16, color = "black"),
axis.text.y = element_blank(),
axis.title.y = element_blank())
ggarrange(p1,p2,nrow = 1)
You can pivot_longer your dataframes, and then use facet_wrap:
df = tidyr::pivot_longer(mtcars, cols=c("disp", "hp"))
ggplot(df) +
geom_point(aes(x=value,y=mpg)) +
facet_wrap(vars(name)) +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 16, color = "black"),
axis.text.y = element_text(size = 16, color = "black"))
Output:

How can I resize the plot in order to be used in R Markdown?

I've created the attached plot using the mentioned code, however, the height of the whole plot looks a bit large and the blank area between the plot and the legend does not seem suitable.
I want to resize the plot in order to use it later in R Markdown presentation. I've seen some posts about resizing the plots but they have all been about resizing the plot for saving purposes. I want to get a plot that looks similar to the one created by Urban Institute Style Guide.
ggplot(top_five, aes(x= Year, y = Production, fill = Country)) +
geom_bar(stat = "identity", position = "dodge") +
theme_minimal() +
scale_fill_manual(values = c("#375E97", "#FB6542", "#FFBB00", "#3F681C", "#98DBC6")) +
scale_y_continuous(limits = c(0,30000), breaks = c(0, 2000, 4000, 6000, 8000, 10000, 12000, 14000), labels = scales::comma) +
theme(axis.title.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
legend.title = element_blank(),
axis.text.y = element_text(size = 12, colour = "black"),
axis.text.x = element_text(size = 12, colour = "black"),
axis.title.y = element_blank(),
legend.position = "top",
legend.key.height = unit(0.8, "lines"),
legend.key.width = unit(0.8, "lines"),
legend.text = element_text(size = 12, colour = "black", face = "bold")) +
labs(title= "Top Five Oil-Producing Countries (2012-2017)", subtitle = "Thousand Barrels Daily",
caption = "Source: BP Statistical Review") +
theme(title = element_text(size = 12)) +
theme(legend.position=c(0,1),
legend.direction="horizontal",
legend.justification=c(0, 1))
My Plot
Urban Institute's Plot

Resources