I'm curious if there is a way to overlay labels on a line graph on ggplot2 to avoid going through the line. I've used vjust, which works in most instances, but when there is a large increase or decrease between two dates the line goes through the label making it hard to read. I will put the plot I'm currently using below and the code. In this instance, I'm wanting to move the 920; 1,467; and 1,480 off the line. I'm exporting the plot to powerpoint via the Reporters package, so I can move it manually, I was just wondering if there was a way to avoid that.
Code:
library("ggplot2")
library("scales")
line_data <- c(276, 475, 753, 840, 931, 962, 801, 920, 1467, 1840, 1737, 1638, 1789, 1733, 1480, 1464, 1538)
year_data <- c(2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
2017)
line_data_total <- as.data.frame(cbind(line_data, year_data))
limit_func <- function(x) {
if (nchar(max(x)) == 2){
round(max(x +5), digits = -1)
} else if (nchar(max(x)) == 3){
round(max(x +50), digits = -2)
} else if (nchar(max(x)) == 4){
round(max(x +500), digits = -3)
}
}
ggplot(data = line_data_total, aes(x = year_data, y = line_data, group = 1)) +
geom_line(color = "red", size = 1.2)+
geom_point(color = "red", fill = "red", shape = 23, size = 1.75) +
geom_text(aes(label = paste0(format(round(as.numeric(line_data), 1), nsmall = 0, big.mark = ","))),
size = 3, fontface = "bold", vjust = -2) +
labs(x = '', y = '') +
expand_limits(y = c(0, limit_func(line_data_total$line_data))) +
scale_x_continuous(breaks = seq(min(line_data_total$year_data), max(line_data_total$year_data), 1)) +
scale_y_continuous(labels = comma) +
theme(panel.grid.major.x = element_blank() ,
panel.grid.major.y = element_line( size=.1, color="light gray"),
panel.background = element_rect(fill = "transparent"),
plot.background = element_rect(fill = "transparent"),
axis.text.x = element_text(face = "bold", size = 10),
axis.text.y = element_text(face = "bold", size = 10),
axis.ticks.y = element_blank())
How about using the
ggplot2
extensionggrepel
:require(ggrepel)
Replace your
geom_text()
line with:nudge_y
is what is pushing the labels off the line, you could use a combination ofnudge_x
andnudge_y
for more control. And see the package vignette: https://github.com/slowkow/ggrepel/blob/master/vignettes/ggrepel.md