Align 2 ggplot graphs on two different slides - r

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}

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)

Legend title not displayed in ggplot-maps

As soon as I add a dynamic range for my legend labels within the scale_fill_distiller-option, I get only a "1" instead the defined legend title within labs(fill="title"). What do I have to change?
Here is my code:
map <- ggplot()+
geom_sf(data=data, aes(fill=Count_Number)) +
labs(title="Chart Title",
x="",y="") +
labs(colour = "Legend Title") +
scale_fill_distiller(palette ="RdBu", direction = -1, na.value="#ffffff",
range(c(min(data$Count_Number, na.rm=T),max(data$Count_Number,na.rm=T))),
breaks = seq(min(data$Count_Number, na.rm=T),max(data$Count_Number, na.rm=T),by=2)) +
theme_opts +
theme(plot.title = element_text(size=12, face="bold")) +
theme(legend.position="bottom") +
theme(legend.key.width=unit(2,"cm")) +
theme(legend.title=element_text(size=11)) +
theme(legend.text=element_text(size=12)) +
theme(legend.key.size = unit(0.5, "cm")) +
ggrepel::geom_label_repel(
data = gmddata_covid,
aes(label = Case, geometry = geometry),
stat = "sf_coordinates",
min.segment.length = 0,
color = "#333333",
segment.color = "white",
size = 2.5
)
Thanks in advance for any help

Change the font size of variable names in ggplot

I am not able to increase the font size of the names of the variables in a graphic realized with ggplot.
I tried to include these codes inside ggplot code, but unsuccessfully :
theme(text = element_text(size=20))
theme(axis.text=element_text(size=20))
theme(axis.title=element_text(size=14))
theme_grey(base_size = 20)
geom_text(size=20)
My code is :
library(ggplot2)
library(reshape2)
dataplot <- read.csv("/Documents/R.csv",header=T,sep=";")
dataPlotMelt <- melt(data = dataplot, id.vars = c("variable"),variable.name = "Method",value.name = "SMD")
varNames <- as.character(dataplot$variable)
dataPlotMelt$variable <- factor(dataPlotMelt$variable,levels = varNames)
ggplot(data=dataPlotMelt,mapping=aes(x=variable,y=SMD,group=Method, color=Method))+
ylab("Standardizedmeandifference(%)")+
xlab("") +
geom_point(aes(shape=Method),size=2) +
geom_hline(yintercept=15,color="black",size=0.1,linetype="dashed") +
geom_hline(yintercept=-15,color="black",size=0.1,linetype="dashed") +
coord_flip() +
theme(axis.text.x=element_blank()) +
scale_y_continuous(breaks=c(-65,-15,15,105)) +
theme_bw() +
theme(legend.text=element_text(size=12)) +
theme(legend.title=element_blank(),legend.key=element_blank()) +
scale_colour_manual(values=c("grey","black"))
I'd like to increase the font size of the names of the variables in the graphic and, besides, increase the text "Standardized mean difference (%)" and remove the vertical line between the yintercept and ybreak on both sides
new graphic
Thank you Richard for giving me the solution.
As you suggested I used theme after theme_bw
I managed to suppress the useless vertical lines as well with the command theme(panel.grid.minor = element_blank())
Here is the new code for ggplot :
ggplot(data = dataPlotMelt, mapping = aes(x = variable, y = SMD,group = Method,
color = Method)) +
ylab("Standardized mean difference (%)") + xlab("") +
geom_point(aes(shape = Method),size=2) +
geom_hline(yintercept = 15, color = "black", size = 0.1, linetype = "dashed") +
geom_hline(yintercept = -15, color = "black", size = 0.1, linetype = "dashed") +
coord_flip() +
theme(axis.text.x = element_blank()) +
scale_y_continuous(breaks=c(-65,-15,0,15,105)) +
theme_bw() + theme(legend.text = element_text(size=13)) +
scale_colour_manual(values= c("grey","black")) +
theme(axis.text.y = element_text(size=12)) +
theme(axis.title.x = element_text(size=13)) +
theme(panel.grid.minor = element_blank()) +
theme(legend.title = element_blank(), legend.key=element_blank())

Remove decimals y axis ggplot2

I have data that looks like this, df_Filtered:
Product Relative_Value
Car 0.12651458
Plane 0.08888552
Tank 0.03546231
Bike 0.06711630
Train 0.06382191
I want to make a bar plot of the data in GGplot2:
ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
scale_y_continuous(labels = scales::percent) +
geom_bar(stat = "identity") +
theme_bw() +
theme(plot.background = element_rect(colour = "black", size = 1)) +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5))
labs(x ="Product", y = "Percentage of total sell", title = "Japan 2010") +
theme(panel.grid.major = element_blank())
How do i get rid of the decimals on the y-axis in the chart? So that it says 20 % instead of 20.0 %?
Use percent_format from the scales package to set accuracy to 1.
library(ggplot2)
library(scales)
ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
scale_y_continuous(labels = percent_format(accuracy = 1)) +
geom_bar(stat = "identity") +
theme_bw() +
theme(plot.background = element_rect(colour = "black", size = 1)) +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5)) +
labs(x ="Product", y = "Percentage of total sell", title = "Japan 2010") +
theme(panel.grid.major = element_blank())
DATA
df_Filtered <- read.table(text = "Product Relative_Value
Car 0.12651458
Plane 0.08888552
Tank 0.03546231
Bike 0.06711630
Train 0.06382191",
header = TRUE, stringsAsFactors = FALSE)
scales::percent_format(accuracy = 2) doesn't allow manual breaks = c(0, 0.5, .10).
So, I have to create the manual function scale_y_continuous(breaks = c(0, 0.5, .10), labels = function(x) paste0(round(as.numeric(x*100)), "%")) .

Wrapping legend in r

Is there a way to wrap the legend so that it goes to the new line or column in r? Even tried to reduce the size but din't work.
Image of my plot-notice legend in overflowing
p <- ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
p + geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort') + theme(legend.position="bottom",panel.background=element_rect(fill = "light grey"),legend.text = element_text(size = 7),legend.key.size = unit(0.25, "cm"))
You can use guides() and pick the number of rows of your legend that looks most attractive:
p <- ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
p + geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort') + theme(legend.position="bottom",panel.background=element_rect(fill = "light grey"),legend.text = element_text(size = 7),legend.key.size = unit(0.25, "cm")) +
guides(fill = guide_legend(nrow = 3)) # or experiment with other numbers of rows

Resources