Reputation: 61
The question probably sounds confusing, so here are a couple of pictures to illustrate what I am trying to achieve.
I somewhat know about the directlabels package and how to avoid clipping. But I cannot find anything about adding arrows/lines that labels and points to each line. I have plots with many more lines that are clustered together, so the arrows would really help.
Here is my code if you want to reproduce this plot. Thanks.
library(ggplot2)
year <- 2008:2018
cvd <- rnorm(11, 15, 1)
alz <- rnorm(11, 10, 0.5)
ui <- rnorm(11, 9, .8)
stro <- rnorm(11, 6, 3)
df <- data.frame("Year" = as.factor(rep(year, 4)), "Number of Deaths" = c(cvd, alz, ui, stro), "Cause of Death" = c(
rep("Cardiovascular Disease", 11),
rep("Alzheimers Disease", 11),
rep("Unidentified Cause of Death", 11),
rep("Stroke", 11)
))
ggplot(data=df, aes(x=Year, y=Number.of.Deaths, group=Cause.of.Death, color = Cause.of.Death)) + geom_line() +
theme(legend.position = "none")
Upvotes: 0
Views: 518
Reputation: 908
I'd look into library(ggrepel).
This is close to what you are looking for:
library(ggplot2)
library(data.table)
library(ggrepel)
year <- 2008:2018
cvd <- rnorm(11, 15, 1)
alz <- rnorm(11, 10, 0.5)
ui <- rnorm(11, 10, .5)
stro <- rnorm(11, 6, 3)
df <- data.frame("Year" = rep(year, 4), "Number of Deaths" = c(cvd, alz, ui, stro), "Cause of Death" = c(
rep("Cardiovascular Disease", 11),
rep("Alzheimers Disease", 11),
rep("Unidentified Cause of Death", 11),
rep("Stroke", 11)
))
#Sorry, I think in terms of data.table.
dt <- data.table(df)
dt2 <- dt[Year==2018]
ggplot(data=dt, aes(x=Year, y=Number.of.Deaths, group=Cause.of.Death, color = Cause.of.Death)) +
geom_line() +
geom_text_repel(data=dt2,
aes(x=Year,y=Number.of.Deaths,label=Cause.of.Death),
direction = "y",
nudge_x = .5,
hjust=0,
size=3,
segment.size = .2,
segment.colour = "black")+
#xlim(c(2008,2020))+
scale_x_continuous(breaks=2008:2018,limits = c(2008,2020))+
theme_minimal()+
theme(legend.position = "none")
Upvotes: 2