How do I customize the margin and label settings with plot_grid? - r

I would like to have the title not be chopped off and have the axis labels removed from this chart that I generated with plot_grid from cowplot.
Here is my code
data(mtcars)
library(ggplot2)
library(cowplot)
mpg = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) +
coord_flip()
am=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) +
coord_flip()
vs=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
coord_flip()
gear = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
coord_flip()
p=plot_grid(mpg,am,vs,gear, labels = "Variables effecting Mileage", label_size = 14, hjust = -0.5,
+ vjust = 0.5)+theme_grey()
p
Also, if it would be simpler to create this without cowplot, what do you suggest?

Here is a cowplot only answer. It might be more what you want.
library(ggplot2)
library(cowplot)
library(gtable)
data(mtcars)
mpg = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) +
coord_flip() + labs(x="",y="")
am=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) +
coord_flip()+ labs(x="",y="")
vs=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
coord_flip()+ labs(x="",y="")
gear = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
coord_flip()+ labs(x="",y="")
p=plot_grid(mpg,am,vs,gear) +
theme_grey() +
# Use annotation text as it is centered at the x,y point
annotate("text",x=0.5,y=1.04,size=7,label="Variables affecting Mileage") +
# Add some space around the edges
theme(plot.margin = unit(c(1,0.5,0.5,0.5), "cm"))
# Suppress tick marks
p=p+scale_y_continuous(breaks=NULL)+scale_x_continuous(breaks=NULL)
# Have to turn off clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
# need to draw it with the new clip settings
grid.draw(gt)
Yields:

would this workout for you?
library(ggplot2)
library(gridExtra)
a <- ggplot() + geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) + coord_flip() + theme_grey() + theme(axis.title.x = element_blank())
b <- ggplot() + geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) + coord_flip() + theme_grey() + theme(axis.title.x = element_blank())
c <- ggplot() + geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
coord_flip() + theme_grey() + theme(axis.title.x = element_blank())
d <- ggplot() + geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
coord_flip() + theme_grey() + theme(axis.title.x = element_blank())
grid.arrange(a, b, c, d, ncol=2, top = "Variables effecting Mileage")

Thanks Mike. This does the job.
data(mtcars)
library(ggplot2)
library(cowplot)
library(gtable)
mpg = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) +
coord_flip() + labs(x="",y="")
am=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) +
coord_flip()+ labs(x="",y="")
vs=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
coord_flip()+ labs(x="",y="")
gear = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
coord_flip()+ labs(x="",y="")
p=plot_grid(mpg,am,vs,gear,
labels = "Variables effecting Mileage",
label_size = 14, hjust = -1.3[![enter image description here][1]][1], vjust = -0.1)+
theme_grey() +
# Add some space around the edges
theme(plot.margin = unit(c(1,0.5,0.5,0.5), "cm"))
# Suppress tick marks
p=p+scale_y_continuous(breaks=NULL)+scale_x_continuous(breaks=NULL)
# Have to turn off clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
# need to draw it with the new clip settings
grid.draw(gt)
Here is my plot

Related

use if else within ggplot chunk to change colour palette

I'd like to be able to change the colour palette in ggplot2 boxplots, according to another variable data_origin.
This makes my boxplots, complete with legend:
library(hrbrthemes)
library(ggplot2)
library(reshape2)
library(tidyverse)
data_origin <- "airborne"
mytitle <- "something more than this"
legend_title <- "some words"
melted <- reshape2::melt(iris)
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
scale_fill_brewer(palette = "Greens") +
theme(
legend.position = "bottom",
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free")
bp1
This however drops the legend completely and ignores the if else:
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
scale_fill_brewer(legend_title, if (data_origin == "airborne" ) {palette = "Blues"} else {palette = "Greens"}) +
theme(
legend.position = "bottom",
# legend.title = legend_title,
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free")
bp1
Besides what #stefan suggested, there are two ways in which you can do this (that I know of). The first is using ifelse() (I moved the relevant part to the end):
data_origin <- "airborne"
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
theme(
legend.position = "bottom",
# legend.title = legend_title,
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free") +
scale_fill_brewer(legend_title, palette = ifelse(
data_origin == "airborne",
"Blues",
"Greens"
))
bp1
The other one is to build the plot up in two steps:
data_origin <- "not airborne"
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
theme(
legend.position = "bottom",
# legend.title = legend_title,
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free")
if (data_origin == "airborne") {
bp2 <- bp1 +
scale_fill_brewer(legend_title, palette = "Blues")
} else {
bp2 <- bp1 +
scale_fill_brewer(legend_title, palette = "Greens")
}
bp2
Created on 2021-08-01 by the reprex package (v2.0.0)

ggplot2 legend in 2 rows

I was unable to find a solution for putting ggplot2 legend in 2 rows.
Example
library(ggplot2)
theme_set(theme_bw())
data("midwest", package = "ggplot2")
ggplot(midwest, aes(x=area, y=poptotal)) +
geom_point(aes(col=state, size=popdensity)) +
geom_smooth(method="loess", se=F) +
xlim(c(0, 0.1)) +
ylim(c(0, 500000)) +
labs(y="Population",
x="Area",
title="") +
theme(legend.position = "top")
In the above image, I would like to have popdensity annotation on top (first row) and state annotation in the second row.
I think you're looking for theme(legend.box = "vertical") and guide_legend(order = ...)
library(ggplot2)
data("midwest", package = "ggplot2")
ggplot(midwest, aes(x=area, y=poptotal)) +
geom_point(aes(col=state, size=popdensity)) +
geom_smooth(method="loess", se=F) +
xlim(c(0, 0.1)) +
ylim(c(0, 500000)) +
labs(y="Population",
x="Area",
title="") +
theme_bw() +
theme(legend.position = "top",
legend.box = "vertical") +
guides(size = guide_legend(order = 1),
colour = guide_legend(order = 2))

Reordering Plot and Changing Axis Size (R ggplot)

I'm trying to change in both of my plots, the order and the x axis size for both. These are not being able to be changed accordingly
DF Creation
contig_count_average <- data.frame(Genome_Type = c("MBT", "Anglucyclines", "Whole Genome"),
Contig_Count_Average = c("2.91","83.7","608.3"))
Plot
p2 <- ggplot(contig_count_average, mapping = aes(x = reorder(Genome_Type, Contig_Count_Average), Contig_Count_Average, fill = Genome_Type)) +
xlab("Genome") +
ylab("Contig No.") +
ggtitle("Contig Count per Genome Distribution") +
geom_bar(stat = "identity") +
theme(text = element_text(size=20),
axis.text.x = element_text(angle=90, hjust=1)) +
guides(fill=guide_legend(title="Genome Type")) +
coord_flip() +
theme_bw() +
scale_y_continuous(limits = c(0,2835), expand = c(0, 0)) +
scale_x_discrete(labels = abbreviate)
p
I get the following warning:
1: In Ops.factor(Contig_Count_Average) : ‘-’ not meaningful for factors
The issue is because Contig_Count_Average is treated as factors in contig_count_average.
We can change it to numeric by doing either :
contig_count_average <- type.convert(contig_count_average, as.is = TRUE
Or
contig_count_average$Contig_Count_Average <- as.numeric(as.character(contig_count_average$Contig_Count_Average))
and then use the ggplot code.
p2 <- ggplot(contig_count_average, mapping = aes(x = reorder(Genome_Type,
Contig_Count_Average), Contig_Count_Average, fill = Genome_Type)) +
xlab("Genome") +
ylab("Contig No.") +
ggtitle("Contig Count per Genome Distribution") +
geom_bar(stat = "identity") +
theme(text = element_text(size=20),
axis.text.x = element_text(angle=90, hjust=1)) +
guides(fill=guide_legend(title="Genome Type")) +
coord_flip() +
theme_bw() +
scale_y_continuous(limits = c(0,2835), expand = c(0, 0)) +
scale_x_discrete(labels = abbreviate)
p2
Also note that you can use geom_col instead of geom_bar(stat = "identity").

"Thermal Bar" plot in R?

I want to create a plot with a single vertical bar (colored continuously), with a mark on it showing the score for a particular person. Image:
I can generate the colored bar in ggplot, but only as a legend (not the actual plot). For example the legend resulting from the following is fine:
ggplot(mtcars, aes(x=wt, y=mpg, color=mpg)) +
geom_point() +
scale_color_gradientn(colors = rainbow(5))
Is there any way to do this? Any help would be really appreciated - I'm completely stuck on this.
ggplot(data.frame(y = 51), aes( y=y)) +
geom_tile(data = data.frame(y = 0:100),
aes(x= 0.5, y = y, fill = y)) +
geom_segment(aes(x=0, xend=1, yend=y)) +
geom_text(aes(label = y, x = 1), hjust = -0.3) +
coord_cartesian(clip = "off", xlim = c(0,1.2)) +
scale_fill_gradientn(colors = rainbow(5)) +
scale_x_continuous(labels = NULL) +
guides(fill = FALSE) +
theme_minimal() +
theme(line = element_blank()) +
labs(x="", y = "")

Align 2 ggplot graphs on two different slides

Dear All,
I want to make 2 choropleths to be put in 2 consecutive slides in a beamer presentation. The boundaries are the same but the fill color is different, so that when I go from the first slide to the second one,the map should not move, but only flip fill colors.
My problem is that I use the SAME incantation of ggplot (except for the fill colour) 2 times to make the 2 graphs and yet the 2 graphs are not aligned so that when I transition from the first slide to the second,I can see the second graph shift a little along the horizontal direction.
Due to the confidential nature of the data I am unable to paste my example.
# This example is from :
# https://medium.com/#anjesh/step-by-step-choropleth-map-in-r-a-case-of-mapping-nepal-7f62a84078d9
library(rgdal)
library(ggplot2)
library(dplyr)
library(broom)
# clone NepalMaps from https://github.com/anjesh/NepalMaps
# read shapefile
nepal.adm3.shp <- readOGR(dsn="./NepalMaps-master/baselayers/NPL_adm", layer="NPL_adm3", stringsAsFactors = FALSE)
# tidy shapefile data to data frame
nepal.adm3.shp.df <- tidy(nepal.adm3.shp, region = "NAME_3")
#write districts to csv file
mydata <- nepal.adm3.shp.df %>%
distinct(id) %>%
write.csv("districts.csv", row.names = FALSE)
mydata <- read.csv("districts.csv")
# Make fake data
mydata$Var1 = as.factor(sample(c(1:5,NA),nrow(mydata),replace= TRUE))
mydata$Var2 = as.factor(sample(c(1:5,NA),nrow(mydata),replace= TRUE))
mydata$Var3 = as.factor(sample(c(1:5,NA),nrow(mydata),replace= TRUE))
myshapeAndData <- left_join(nepal.adm3.shp.df,mydata,by="id")
library(scales)
library(ggplot2)
library(RColorBrewer)
# Plot using ggplot2.
# EXACT same Graphs,EXCEPT,with different lengths of title / legend title (padded with spaces to make them of equal length)
# The graphs move on transitioning from one slide to the other. I have padded the plot title / legend title with spaces to make them have the same length but it does NOT work.
ggplot() +
geom_polygon(data = myshapeAndData, aes(x=long,y=lat,group = group,fill = Var1),color= "black") +
scale_fill_manual(name ="Var1 ",values = brewer.pal(5,"Greens"),na.value = "pink") +
theme(plot.margin = unit(c(.4,.8,.3,.2), "in")) +
xlab("") +
ylab("") +
theme(legend.key.size = unit(1, "cm")) +
theme(legend.text=element_text(size=15),axis.text=element_text(size=15),plot.title = element_text(size=20),legend.title =element_text(size=15),axis.title = element_text(size=15)) +
ggtitle("Title Length 1 ") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_fixed(ratio = 5.6/3.8)
ggsave("graph1.pdf",height =38/4,width = 56/4,units="in")
ggplot() +
geom_polygon(data = myshapeAndData, aes(x=long,y=lat,group = group,fill = Var2),color = "black") +
scale_fill_manual(name = "My var 2 ",values = brewer.pal(5,"Greens"),na.value = "pink") +
theme(plot.margin = unit(c(.4,.8,.3,.2), "in")) +
xlab("") +
ylab("") +
theme(legend.key.size = unit(1, "cm")) +
theme(legend.text=element_text(size=15),axis.text=element_text(size=15),plot.title = element_text(size=20),legend.title =element_text(size=15),axis.title = element_text(size=15)) +
ggtitle("My title Length 2 ") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_fixed(ratio = 5.6/3.8)
ggsave("graph2.pdf",height = 38/4,width = 56/4,units="in")
ggplot() +
geom_polygon(data = myshapeAndData, aes(x=long,y=lat,group = group,fill = Var3),color = "black") +
scale_fill_manual(name = "3rd Variable",values = brewer.pal(5,"Greens") ,na.value = "pink") +
theme(plot.margin = unit(c(.4,.8,.3,.2), "in")) +
xlab("") +
ylab("") +
theme(legend.key.size = unit(1, "cm")) +
theme(legend.text=element_text(size=15),axis.text=element_text(size=15),plot.title = element_text(size=20),legend.title =element_text(size=15),axis.title = element_text(size=15)) +
ggtitle("My title-testing three") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_fixed(ratio = 5.6/3.8)
ggsave("graph3.pdf",height = 38/4,width = 56/4,units="in")
# EXACT same graphs.
# All graphs with the same length of plot title and legend title.
# This works. The graphs do not move on transitioning,they only flip colors.
ggplot() +
geom_polygon(data = myshapeAndData, aes(x=long,y=lat,group = group,fill = Var1),color= "black") +
scale_fill_manual(name ="Var1",values = brewer.pal(5,"Greens"),na.value = "pink") +
theme(plot.margin = unit(c(.4,.8,.3,.2), "in")) +
xlab("") +
ylab("") +
theme(legend.key.size = unit(1, "cm")) +
theme(legend.text=element_text(size=15),axis.text=element_text(size=15),plot.title = element_text(size=20),legend.title =element_text(size=15),axis.title = element_text(size=15)) +
ggtitle("Title1") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_fixed(ratio = 5.6/3.8)
ggsave("graph1.pdf",height =38/4,width = 56/4,units="in")
ggplot() +
geom_polygon(data = myshapeAndData, aes(x=long,y=lat,group = group,fill = Var2),color = "black") +
scale_fill_manual(name = "Var2",values = brewer.pal(5,"Greens"),na.value = "pink") +
theme(plot.margin = unit(c(.4,.8,.3,.2), "in")) +
xlab("") +
ylab("") +
theme(legend.key.size = unit(1, "cm")) +
theme(legend.text=element_text(size=15),axis.text=element_text(size=15),plot.title = element_text(size=20),legend.title =element_text(size=15),axis.title = element_text(size=15)) +
ggtitle("Title2") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_fixed(ratio = 5.6/3.8)
ggsave("graph2.pdf",height = 38/4,width = 56/4,units="in")
ggplot() +
geom_polygon(data = myshapeAndData, aes(x=long,y=lat,group = group,fill = Var3),color = "black") +
scale_fill_manual(name = "Var3",values = brewer.pal(5,"Greens") ,na.value = "pink") +
theme(plot.margin = unit(c(.4,.8,.3,.2), "in")) +
xlab("") +
ylab("") +
theme(legend.key.size = unit(1, "cm")) +
theme(legend.text=element_text(size=15),axis.text=element_text(size=15),plot.title = element_text(size=20),legend.title =element_text(size=15),axis.title = element_text(size=15)) +
ggtitle("Title3") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_fixed(ratio = 5.6/3.8)
ggsave("graph3.pdf",height = 38/4,width = 56/4,units="in")
Here is the latex file to display the graphs.
\documentclass{beamer}
\usetheme{CambridgeUS}
\usepackage{amssymb,amsmath}
\usepackage{listings}
\usepackage{hyperref}
\usepackage{fancyvrb}
\title[]{Testing maps}
\author{}
\begin{document}
\maketitle
\begin{frame}
\centering
\begin{tabular}{c}
\includegraphics[width=0.9\linewidth]{graph1.pdf}
\end{tabular}
\end{frame}
\begin{frame}
\centering
\begin{tabular}{c}
\includegraphics[width=0.9\linewidth]{graph2.pdf}
\end{tabular}
\end{frame}
\begin{frame}
\centering
\begin{tabular}{c}
\includegraphics[width=0.9\linewidth]{graph3.pdf}
\end{tabular}
\end{frame}
\end{document}

Resources