Reputation: 101
I have created a graph to demonstrate the development of four variables. Is there any way to add a label that tells the percentage change(last observation/first observation -1) to the end of the plots to highlight the relative change during the observed period?
Data&plots=
library(tidyverse)
Data <- data.frame(
Wind = c(236,325,470,615,647,821),
Hard_coal= c(591,811,667,681,532,344),
Gas= c(883,841,472,731,678,680),
Bio = c(883,841,811,731,678,680),
year= c("2015","2016","2017","2018","2019","2020"))
Data %>%
pivot_longer(-year) %>%
ggplot(aes(x = year, y = value, color = name, group = name, linetype = name)) +
geom_line(size = 1.5)
Upvotes: 2
Views: 1012
Reputation: 125163
Using the ggrepel
option offered in Plot labels at ends of lines this could be achieved like so where I make use of dplyr
s first
and last
to compute the percentage change.
Note: I still vote to close this question as a duplicate.
library(tidyr)
library(dplyr)
library(ggplot2)
data_long <- Data %>%
pivot_longer(-year) %>%
mutate(year = as.numeric(year)) %>%
group_by(name) %>%
mutate(change = last(value) / first(value) - 1)
ggplot(data_long, aes(x = year, y = value, color = name, group = name)) +
geom_line(size = 1) +
ggrepel::geom_text_repel(data = filter(data_long, year == max(year)),
aes(label = scales::percent(change)),
direction = "y", nudge_x = .25,
hjust = 0, show.legend = FALSE) +
scale_x_continuous(limits = c(NA, 2020.5)) +
coord_cartesian(clip = "off")
Upvotes: 1