Good!!!
I have one last difficulty : I will make this code a function, so the values and their magnitude will be variable.
I have a problem with the position of the text on the columns.
For example with these 2 df :
#goat
annee <- c(2021, 2021, 2021, 2021, 2021, 2021,2021, 2021, 2021, 2021, 2021, 2021, 2022, 2022, 2022,2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022)
mois <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4,5, 6, 7, 8, 9, 10, 11)
espece <- c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
moy <- c(45.57, 43.92, 42.44, 39.55, 37.52, 34.81, 34.65, 35.2, 36.76, 41.64, 45.14, 46.34, 44.68, 44.22, 42.16, 39.64,36.15, 34.59, 34.13, 33.71, 36.5, 39.55, 42.53)
df <- tibble(annee,mois,espece,moy)
#cow
annee <- c(2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022)
mois <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
espece<- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1)
moy <- c(43.89, 43.15, 42.88, 42.18, 42.04, 41.2, 41.1, 41.73, 42.28, 43.43, 44.32, 44.33, 43.23, 42.65, 42.28, 41.79, 40.64, 40.4, 40.42, 40.87, 42.24, 43.32, 43.6)
df <- tibble(annee,mois,espece,moy)
this is R code with few changes
N <- 2022
mg <- df %>%
mutate(annee=case_when(annee==N ~ "N",
annee==N-1 ~ "N_1")) %>%
pivot_wider(names_from = annee, values_from=moy) %>%
mutate(ecart=N-N_1) %>%
mutate(mois=as.factor(mois)) %>%
select(-espece)
mg_long <- mg %>%
pivot_longer(cols=c("N_1","N"), names_to="annee",values_to="moy")
mean_mg <- round(mean(mg_long$moy, na.rm = T),0)
dif_mg <- round(max(mg_long$moy, na.rm = T)-min(mg_long$moy, na.rm = T),0)
ytext <- mg %>%
mutate(ecart2 = ifelse(ecart<0, ecart-0.05, ecart+0.05))
mg %>%
ggplot(aes(x = mois, y = ecart, fill = "ecart")) +
geom_col(width = .4) +
geom_line(data=mg_long,aes(x=mois, y=moy- mean_mg, color = annee, group = annee),
size = 2, stat = "identity", inherit.aes = F) +
scale_y_continuous("", breaks = seq(-dif_mg/2-1, dif_mg/2+1, by = .5),
labels = round(mean_mg+seq(-dif_mg/2-1, dif_mg/2+1, by = .5),2),
sec.axis = sec_axis(~ ., name = ""))+
scale_color_manual(breaks = c("N_1", "N"),
values = c("#00BFC4", "#F8766D")) +
scale_fill_manual(breaks = c("ecart"),
values = c("#4472C4")) +
labs(fill = NULL, color = NULL,
x = NULL, y = NULL) +
geom_text(data = ytext, aes(y = ecart2, label = round(ecart,2)), size=3) +
theme_bw() +
theme(legend.position = "bottom",
panel.grid.major.x = element_blank())
And here are the 2 graphs :
cow :
goat :