I have a 2x2 grid graph with two models' data per panel. I need to have separate regression lines for each model in each panel. Can I do this with facet_grid? I have everything but the regression lines:
df <- data.frame(year=factor(c(2000,2001,2002,2000,2001,2002,2000,2001,2002,2000,2001,2002,
2000,2001,2002,2000,2001,2002,2000,2001,2002,2000,2001,2002)),
crop=c("Maize","Maize","Maize","Maize","Maize","Maize",
"Soybean","Soybean","Soybean","Soybean","Soybean","Soybean",
"Maize","Maize","Maize","Maize","Maize","Maize",
"Soybean","Soybean","Soybean","Soybean","Soybean","Soybean"),
treatment_code=c("T1","T1","T1","T2","T2","T2",
"T1","T1","T1","T2","T2","T2",
"T1","T1","T1","T2","T2","T2",
"T1","T1","T1","T2","T2","T2"),
value=c(9,10,8.5,11,12,7.8,
4,7,7.5,3,3,5,
12,11,9,13,9,10,
5,3,6,4,5,4),
model=c("A","A","A","A","A","A","A","A","A","A","A","A",
"B","B","B","B","B","B","B","B","B","B","B","B"))
gY_calib <- df %>%
ggplot(aes(x=year, y=value, color=model, show.legend=TRUE)) +
geom_point(show.legend=TRUE) +
xlab("Year") +
ylab(expression('Grain Yield (Mg ha ' ^-1*')')) +
ylim(0,13) +
facet_grid(crop~treatment_code)
gY_calib
Your year
is factor. If you make it numeric it will work. You can use the following code
df <- data.frame(year=c(2000,2001,2002,2000,2001,2002,2000,2001,2002,2000,2001,2002,
2000,2001,2002,2000,2001,2002,2000,2001,2002,2000,2001,2002),
crop=c("Maize","Maize","Maize","Maize","Maize","Maize",
"Soybean","Soybean","Soybean","Soybean","Soybean","Soybean",
"Maize","Maize","Maize","Maize","Maize","Maize",
"Soybean","Soybean","Soybean","Soybean","Soybean","Soybean"),
treatment_code=c("T1","T1","T1","T2","T2","T2",
"T1","T1","T1","T2","T2","T2",
"T1","T1","T1","T2","T2","T2",
"T1","T1","T1","T2","T2","T2"),
value=c(9,10,8.5,11,12,7.8,
4,7,7.5,3,3,5,
12,11,9,13,9,10,
5,3,6,4,5,4),
model=c("A","A","A","A","A","A","A","A","A","A","A","A",
"B","B","B","B","B","B","B","B","B","B","B","B"))
ggplot(df, aes(x=year, y=value)) +
geom_point(stat='identity', position='identity', aes(color=model)) +
xlab("Year") +
ylab(expression('Grain Yield (Mg ha ' ^-1*')')) +
ylim(0,13) +
geom_smooth(method='lm', formula= y~x, aes(colour = model)) +
facet_grid(crop~treatment_code) +
scale_x_continuous(labels = scales::label_number(accuracy = 1), n.breaks = 3)