Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic position for ggplot2 objects (especially geom_text)?

Tags:

r

ggplot2

When using ArcGIS to make maps, the software by default pushes point and polygon labels around automatically to avoid overlap using a proprietary algorithm. They refer to this as dynamic labeling. ggplot2 has position_jitter which is excellent for points (since dynamic labeling might create systematic bias), but less good for labels using geom_text.

Here's an example of some problems with jitter that a dynamic labeling algorithm might solve:

library(ggplot2)
ggplot( mtcars,aes( x=wt, y=mpg, label=rownames(mtcars) ) ) +
  geom_point() +
  geom_text( position=position_jitter(h=1,w=1) )

jittered labels with problems noted

Does such a dynamic labeling feature exist already in ggplot2?

If not, what algorithms exist for doing so and is it possible to implement a position_dynamic in R?

like image 279
Ari B. Friedman Avatar asked Aug 09 '11 12:08

Ari B. Friedman


Video Answer


2 Answers

Check out the new package ggrepel. ggrepel provides geoms for ggplot2 to repel overlapping text labels. It works both for geom_text and geom_label.

enter image description here

Figure is taken from this blog post.

like image 200
Sukhi Avatar answered Oct 05 '22 13:10

Sukhi


I ran into a similar problem with several of the plots I have been working with and wrote a basic package that uses force field simulation to adjust object location. While much improvement is possible, including integration with ggplot, etc. it seems to get the task accomplished. The following illustrates the functionality:

install.packages("FField", type = "source")
install.packages("ggplot2")
install.packages("gridExtra")
library(FField)
FFieldPtRepDemo()
like image 44
gregk Avatar answered Oct 05 '22 15:10

gregk