geom_text-使用ggplot2查找质心并在多边形中添加文本- [英] geom_text - finding centroids and adding text in a polygon using ggplot2 -

查看:77
本文介绍了geom_text-使用ggplot2查找质心并在多边形中添加文本-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在多边形地图上创建标签文本层.这是下面两个非常相似的查询:

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

标签中的地图多边形的标签中心R ggplot中地图多边形的中心

在地图上以ggplot为中心的名称

我的数据框如下(为了清楚起见,我简化了long和lat-它们是坐标)

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

非常感谢

推荐答案

在地图上以ggplot为中心的名称

基于上面链接中Andrie的输入,我使用 aggregate()创建了一个新的向量,该向量可以解决问题-尽管使用坐标方法将文本居中在多边形中是有争议的.将查看 coordinates() @RomanLuštrik

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

这篇关于geom_text-使用ggplot2查找质心并在多边形中添加文本-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆