2017-02-14 9 views
0

ポリゴンマップにラベルテキストレイヤーを作成したいと思います。geom_text - ggplot2を使用して重心を検索し、ポリゴンにテキストを追加する -

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 
-

Labeling center of map polygons in R ggplot

ggplot centered names on a map

次のように、(彼らは座標であり、私はわかりやすくするために長いと緯度簡体字)ですマイデータフレーム: これは、以下の2から非常によく似たクエリがあります

これは私の現在のコードです。黒いマップを返します - 私は、すべてのlongとlat座標のテキストがあると仮定します。 私は各ポリゴンのセントロイドを見つけるのに苦労しています。そのため、ポリゴンセンターごとにテキストレイヤーを追加することができます。

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()) 

多くのおかげで上記のリンクでAndrieの入力に基づいて

+1

になります[_reproducible_](http://stackoverflow.com/questions/5963269)あなたの例をしてください。 – Axeman

+0

リンクのおかげで、編集される - それは、私は数多くのポリゴンを持っているので、いくつかの座標を追加するために複雑になるので、私のdfの観測。 – Chrisftw

+2

適切な 'sp'オブジェクトを持っているなら' coordinates() 'はポリゴンの重心を与えるでしょう。 –

答えて

1

Andrie's asnwer on ggplot centered names on a map

は、私は、トリックを行いますaggregate()で新しいベクトルを作成 - 座標の手段を用いてポリゴン内のセンタリングテキストであるが、議論の余地がある。 coordinates() @RomanLuš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()) 
関連する問題