So, I have a dataset which looks like this.
I'm tasked with creating a smooth faceted visualization which shows each coral's bleaching rate at each site which I've successfully done so like this:
(I FULLY realize that this code might be bad and have some mistakes in it and I'd really appreciate it if people could tell me ways to improve it or correct some grave errors in it).
coral_data <- read.csv("file.csv")
#options(warn=-1)
library(ggplot2)
ggplot(coral_data, aes(x=year, y=value, colour=coralType, group=coralType)) +
geom_smooth(method="lm", se=F) +
scale_x_continuous(name="Year", breaks=c(2010, 2013, 2016)) +
scale_y_discrete(breaks = seq(0, 100, by = 10)) +
facet_grid(coralType ~ location, scales="free")+
expand_limits(y=0) +
labs(x="\nBleaching Rate", y="Year", title="Coral Bleaching for different corals at different sites over the years\n")
But, I also have to order the facets by lattitudes (currently, its like site01, site02, etc but I want the faceted sites to be ordered w.r.t. their lattitude values, be it ascending or descending) but sadly I have no idea as to how I'm going to do that.
Thus, could someone please tell me how to go about doing this?
Consider ordering your data frame by latitude, then re-assign location factor variable by defining its levels to new ordering with unique
:
# ORDER DATA FRAME BY ASCENDING LATITUDE
coral_data <- with(coral_data, coral_data[order(latitude),])
# ORDER DATA FRAME BY DESCENDING LATITUDE
coral_data <- with(coral_data, coral_data[order(rev(latitude)),])
# ASSIGN site AS FACTOR WITH DEFINED LEVELS
coral_data$location <- with(coral_data, factor(as.character(location), levels = unique(location)))
ggplot(coral_data, ...)