This post is my attempt to apply what I have just read on R-bloggers “Repel overlapping text labels in ggplot2” by Stephen Turner.
library(reshape2)
library(ggplot2)
library(dplyr)
data(diamonds)
if(!require("ggrepel")){
devtools::install_github("slowkow/ggrepel")
}
library(ggrepel)I will use the diamond data to demonstrate for a quick and dirty demo:)
diamonds %>%
filter(cut=="Ideal") %>% #filter only 1 carat
filter(carat>=0.9) %>% #cut of the little ones
filter(carat<=1.1) %>% #remove the hellishly expensive ones
filter(clarity %in% c("VVS1", "VVS2")) %>% #filter only the most clear ones
mutate(label=apply(.[,c("color", "clarity", "depth", "table")],1,function(x){
return(paste(x, collapse = "|")) #form the labels
})) %>%
select(carat, price, label) -> diamonds.selection #select that stuff that will go into the plot
diamonds.selection %>% ggplot(data=., mapping=aes(x=carat, y=price, color=price)) + geom_point() +
geom_text_repel(data=filter(diamonds.selection, price>1.2e4), aes(label=label)) + #here we only chose the most costly
theme_bw()#btw, this will take some time, as the optimization seems quite costlyAs you can see, not all labels were distributed well, however, much of the potential mess (have we not used the geom_text_repel) is gone. Please check out the original source, all credit to Stephen Turner, like, share, tweet, g+ his post!