0

I'd like to automatically adjust the position of values in a graph. Please consider the following:

enter image description here

As you can see, the values overlap with the line. How do I avoid this? I can, of course, manually change the position of all values but it would be rather hard to adjust all values.

My code is:

library(ggplot2)
library(scales)

df <- data.frame(years=c(1989, 1991, 1993, 1997, 2001, 2005, 2007, 2011, 2015),
                 freq=c(62.70, 43.20, 52.13, 47.93, 46.29, 40.57, 53.88, 48.92, 50.92))

df$years <- as.numeric(as.character(df$years))

point <- format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE)

p <- (ggplot(df, aes(x=years, y=freq, label=point(round(freq,1)))) +
        geom_line(size=.7, color="#999999") + 
        geom_point(size=3, color="black") +
        geom_text(vjust=c(2, -1, -1.5*sign(diff(diff(df$freq))) + 0.5)) +
        theme_bw() +
        theme(panel.border=element_blank(), panel.grid.minor=element_blank(),
              axis.text.y=element_blank(), axis.ticks=element_blank(), axis.line.y=element_blank()) +
        scale_x_continuous("", breaks=df$years, minor_breaks=NULL) +
        scale_y_continuous("", limits=c(0, 65),
                           breaks=seq(0, 65, 10), minor_breaks=NULL))
p
menteith
  • 596
  • 14
  • 51
  • Try this [awesome package called ggrepel](https://github.com/slowkow/ggrepel)? – Vincent Guillemot May 02 '16 at 13:13
  • Really awesome. I used `geom_text_repel(aes(years,freq))` instead of `geom_text(vjust=c(2, -1, -1.5*sign(diff(diff(df$freq))) + 0.5))` but there are still overlaps. – menteith May 02 '16 at 13:26
  • 2
    `vjust <- sign(diff(df$freq));vjust <- c(vjust, -1*tail(vjust, 1));vjust <- ifelse(vjust == 1, 2, -1)` and `geom_text(aes(vjust = vjust))` - no collision checks, but just looking at where the line goes next... – lukeA May 02 '16 at 13:39
  • @lukeA Thanks for this. Perfect. – menteith May 02 '16 at 13:43
  • I added a reference to **ggrepel** to the linked duplicate. – joran May 02 '16 at 20:37

0 Answers0