I have some transpiration data from an experiment that I would like to show as a time series on a line graph using R. I also have some precipitation data which I would like
Multiple axis are not available in ggplot
, it's a choice of Hadley Wickham, the creator of the package. You just can't.
Source: https://stackoverflow.com/a/3101876/8031980
As described with nice examples here or here starting with version 2.2.0 of ggplot2
, is possible to add a secondary axis.
One could try this:
ggplot
:# Read data from OP's DropBox links
am_means <- read.csv("https://www.dropbox.com/s/z4dl0jfslhqccb8/am_means.csv?dl=1")
rainfall <- read.csv("https://www.dropbox.com/s/vkv9vm5o93ttk1i/Rainfall.csv?dl=1")
am_means$dates <- as.Date(am_means$dates, format = "%d/%m/%Y")
rainfall$DATE <- as.Date(rainfall$DATE,format = "%d/%m/%Y")
# join the two tables
my_data_all <- merge(x = am_means,
y = rainfall,
by.x = "dates",
by.y = "DATE",
all = TRUE)
# use data between desired date interval (rainfall had some extra dates)
require(data.table)
setDT(my_data_all)
my_data <- my_data_all[dates %between% c("2017-01-31", "2017-04-06")]
Is important to transform the data appearing on 2nd OY (right-hand side). Since the max value is approx 2 times smaller that the one of the data from first OY axis (left-hand side), one can multiply by 2.
my_factor <- 2
my_plot <- ggplot(my_data,
aes(x = dates,
group = Treatment)) +
geom_errorbar(aes(ymin = cond - err,
ymax = cond + err,
colour = Treatment),
width = 0.5,
size = 0.5) +
geom_line(aes(y = cond, colour = Treatment)) +
geom_point(aes(y = cond, colour = Treatment)) +
# here the factor is applied
geom_bar(aes(y = daily.rainfall * my_factor),
fill = "light blue",
stat = "identity")
my_plot
Adding the 2nd OY axis with scale_y_continuous
. Note the transformation back. If above we multiplied by 2, now we divide data by 2:
my_plot <- my_plot + scale_y_continuous(sec.axis = sec_axis(trans = ~ . / my_factor,
name = "Rainfall (mm)"))
Continues with OP's code
my_plot <- my_plot + scale_x_date(date_breaks = "2 weeks",
date_minor_breaks = "1 week",
date_labels = "%b %d") +
scale_color_manual(breaks = c("Control", "T1", "T2", "T3", "T4"),
values = c("blue", "yellow", "hotpink1", "orange", "red")) +
labs(title = "Stomatal Conductance - Tamata Maples",
y = expression(Conductance (m~mol~m^{-2})),
x = "Date") +
theme_bw()
my_plot
Some other related answered questions: adding a cumulative curve or combining Bar and Line chart.