1

I would like to create a label text layer on a polygon map. This is a very similar query from the two below :

Labeling center of map polygons in R ggplot

ggplot centered names on a map

My dataframe is as follows, (I simplified long and lat for clarity - they are coordinates)

id  long   lat   order  hole    piece  group   locid   location

0   long1  lat1  1      false   1      0.1     1       TEXT I WANT
0   long2  lat2  2      false   1      0.1     1       TEXT I WANT
1   long3  lat3  3      false   1      1.1     2       TEXT I WANT2
1   long4  lat4  4      false   1      1.1     2       TEXT I WANT2

This is my current code, it returns a black map - I assume there's text for every long and lat coordinates. I am struggling to find the centroids of each polygon so that i can add a text layer only as per the polygone centre.

testtext <- ggplot() +
           geom_polygon(data = df, mapping = aes(x=long, y=lat, group = group, fill=location)) +
           geom_text(data = df, mapping = aes(x=long, y=lat, group = group, label=location)) +
           geom_path(color = "white") +
           scale_fill_hue(l=40) +
           coord_equal() +
           theme(legend.position = "none", title = element_blank(), axis.text = element_blank())

Many thanks

Community
  • 1
  • 1
Chrisftw
  • 119
  • 1
  • 8
  • 1
    Please make your example [_reproducible_](http://stackoverflow.com/questions/5963269). – Axeman Feb 14 '17 at 12:45
  • thanks for the link, will edit - that being said, it will be complicated to add some coordinates as I have numerous polygons, hence observations in my df. – Chrisftw Feb 14 '17 at 12:51
  • 2
    `coordinates()` will give you centroids of polygons if you have a proper `sp` object. – Roman Luštrik Feb 14 '17 at 12:52

1 Answers1

2

Andrie's asnwer on ggplot centered names on a map

Based on Andrie's input in the above link, I created a new vector with aggregate() that does the trick - although centering text within a polygon using means of coordinates is debatable. Will look into coordinates() @Roman Luštrik

library(ggplot2)
centroid <- aggregate(cbind(long,lat) ~ location, data=df, FUN=mean)
testtext <- ggplot() +
            geom_polygon(data = df, mapping = aes(x=long, y=lat, group = group, fill=location)) +
            geom_text(data = centroid, mapping = aes(x=long, y=lat, label=location)) +
            geom_path(color = "white") +
            scale_fill_hue(l=40) +
            coord_equal() +
            theme(legend.position = "none", title = element_blank(), axis.text = element_blank())
Community
  • 1
  • 1
Chrisftw
  • 119
  • 1
  • 8