I cleaned the R environment, summarized annual rainfall data, created additional three variables, plotted all four variables vs. Year, customized plot theme, customized colors, customized legend, and saved image in the working directory using four different packages. The code and output is presented below in this post.
# House Keeping:
rm(list = ls()) # Clear environment
library(readxl) # Read Excel
library(ggplot2) # Plotting
library(dplyr) # Data Management
setwd("path/to/working/directory")
# Data Management:
my.data = readxl::read_excel("ExcelFileName.xlsx", sheet = "SheetName", col_names = T)
pp.data = my.data %>%
group_by(Year) %>%
summarise(pp_grow = mean(pp_grow, na.rm = T),
gsr.p50 = pp_grow + pp_grow*50/100,
gsr.s50 = pp_grow - pp_grow*50/100)
# Color Designation:
cols = c("GSR + 50%" = "red",
"GSR" = "Purple",
"GSR - 50%" = "green",
"Mean Line" = "orange")
# Plotting:
ggplot(pp.data,aes(x = Year,
y = pp_grow,
color = "GSR")) +
# Rainfall
geom_line(size = 0.75) +
xlim(1985, 2017) +
ylim(0, 2000) +
ylab("Growing Season (Apr.-Sept.) Rainfall (mm)") +
xlab("Year") +
# Theme:
theme(plot.background = element_rect(fill = "white",
color = "black",
size = 0),
panel.background = element_rect(fill = "white",
color = "black",
size = 0),
panel.grid.major.x = element_line(color = "lightgrey",
linetype = 2,
size = 0),
panel.grid.minor.x = element_line(color = "lightgrey",
linetype = 2,
size = 0),
panel.grid.major.y = element_line(color = "grey",
linetype = 2,
size = 0.25),
panel.grid.minor.y = element_line(color = "grey",
linetype = 2,
size = 0.25),
axis.line.x.top = element_line(color = "white",
linetype = 2,
size = 0),
axis.line.y.right = element_line(color = "white",
linetype = 2,
size = 0),
axis.line.x.bottom = element_line(color = "black",
linetype = 1,
size = 0.75),
axis.line.y.left = element_line(color = "black",
linetype = 1,
size = 0.75)) +
# + 50% Rainfll
geom_line(data = pp.data,
aes(y = gsr.p50,
color = "GSR + 50%"),
size = 0.75,
linetype = 2) +
# Mean Line:
geom_line(data = NULL,
aes(y = (meanline = mean(pp_grow)),
color = "Mean Line"),
size = 0.5,
linetype = 2) +
# - 50% Rainfll
geom_line(data = pp.data,
aes(y = gsr.s50,
color = "GSR - 50%"),
size = 0.75,
linetype = 2) +
# Values of Rainfall:
geom_text(aes(label = round(pp_grow, 2)),
color = "black",
size = 2.5,
hjust = "outward",
angle = 90) +
# Adjust Legend:
labs(color = "GS Rainfalls:") +
scale_color_manual(values = cols)
#Save Plot:
ggsave("rainfall.jpeg")

One response to “Customized plot using ggplot2 and dplyr”
[…] can see this figure in my previous post as well. In this post I have taken a different approach of loading data in R. You can manually […]
LikeLike