Hi. How can I put direct labelling into the graph? Like in the below figure, the name of continent must appear next to the line representing the respective continent.
library(tidyverse)
library(janitor)
#>
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#>
#> chisq.test, fisher.test
library(gapminder)
gapminder<-gapminder %>%
clean_names()
gapminder %>%
group_by(continent,year) %>%
summarise(mean_life_exp=mean(life_exp)) %>%
ggplot()+geom_line(mapping=aes(year,mean_life_exp,color=continent),size=1.5)+
theme_minimal()+
labs(title="Trend in life expectancy across continents",x="Year",ÿ="Average Life Expectancy")
#> `summarise()` has grouped output by 'continent'. You can override using the `.groups` argument.
# Data for the plot
plot_gapminder = gapminder %>%
group_by(continent,year) %>%
summarise(mean_life_exp=mean(life_exp))
# find the max points for the text labels
text_gapminder = plot_gapminder %>%
summarise(year = max(year),
life_exp = max(mean_life_exp))
ggplot(plot_gapminder) +
geom_line(mapping=aes(year,mean_life_exp,color=continent),size=1.5)+
theme_minimal()+
labs(title="Trend in life expectancy across continents",
x="Year", y="Average Life Expectancy") +
geom_text(data = text_gapminder,
aes(x = year+1, # adding some offset
y = life_exp,
label = continent, colour = continent),
size = 5,
hjust = 0) +
coord_cartesian(xlim = c(1950, 2012)) + # you may need to adjust this a bit
theme(legend.position = "none")