如何使用ggplot2使用描述关联标签的图例为区域地图添加图例? [英] How to add legend for regional map with a legend describing associated labels using ggplot2?

查看:1114
本文介绍了如何使用ggplot2使用描述关联标签的图例为区域地图添加图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SpatialPoly数据: SpatialData



收益数据:收益数据



代码:

  ##加载包
library(rgdal)
库(plyr)
库(maps)
库(maptools)
库(mapdata)
库(ggplot2)
库(RColorBrewer)
图书馆(外国)
库(sp)

##加载shape文件和.csv文件
#Morocco< - readOGR(dsn =。,layer =Morocco_adm0 )
摩洛哥注册< - readOGR(dsn =。,layer =Morocco_adm1)
摩洛哥方块< - read.csv(file =F:/ Purdue University / RA_Position / PhD_ResearchandDissert / PhD_Draft /国家CGE / RMaps_Morocco / Morocco_Yield.csv,header = TRUE,sep =,,na.string =NA,dec =。,strip.white = TRUE)

# #Reo根据类别变量ID_1,修改shapefile中的数据,并将其更改为dataframe
摩洛哥指数(摩洛哥指数)_摩洛哥证券交易委员会

##通过ID_1从.csv文件中将yield impact列添加到shapefile
##请注意,在.csv文件中,我刚刚添加了列ID_1来匹配它与shapefile
MoroccoReg.df< - cbind(MoroccoReg.df,MoroccoYield,by ='ID_1')

##检查shapefile
属性的结构和内容(MoroccoReg.df)

##为地图定义新的主题
##我在网站上找到了这个功能
theme_map< - function(base_size = 12,base_family = ){
theme_gray(base_size = base_size,base_family = base_family)%+替换%
主题(
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
ax is.ticks.length = unit(0.3,lines),
axis.ticks.margin = unit(0.5,lines),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
legend.background = element_rect(fill =white,color = NA),
legend.key = element_rect(color =white),
legend.key.size = unit(1.5,lines),
legend.position =right,
legend.text = element_text(size = rel(1.2)),
legend.title = element_text(size = rel(1.4),face =bold,hjust = 0),
panel.background = element_blank(),
panel.border = element_blank() ,
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.margin = unit(0,lines),
plot.background = element_blank(),
plot.margin = unit(c(1,1,0.5,0.5),lines),
plot.title = element_text(size = rel(1.8) ,face =bold,hjust = 0.5),
strip.background = element_rect(fill =grey90,color =grey50),
strip.text.x = element_text(size = rel (0.8)),
strip.text。 y = element_text(size = rel(0.8),angle = -90)

}

##绘制

摩洛哥注册地图1< - ggplot (data = MoroccoReg.df,aes(long,lat,group = group))
MoroccoRegMap1< - MoroccoRegMap1 + geom_polygon(aes(fill = A2Med_noCO2))
MoroccoRegMap1< - 摩洛哥注册地图1 + geom_path ='gray',linestyle = 2)
#MoroccoRegMap< - MoroccoRegMap + scale_fill_gradient(low =#CC0000,high =#006600)
摩洛哥注册地图1< - 摩洛哥注册地图1 + scale_fill_gradient2(name = %Change in yield,low =#CC0000,mid =#FFFFFF,high =#006600)
摩洛哥地图1 - 摩洛哥注册地图1 +实验室(标题=SRES_A2,noCO2效应)
MoroccoRegMap1< - MoroccoRegMap1 + coord_equal()+ theme_map()
MoroccoRegMap1

结果:





问题:



在收益数据中,我有一列记录与ID_1列中的每个条目相对应的标签。我想要实现的是两件事:



1)绘制地图,并将ID_1变量条目添加到地图上的标签,从而识别每个区域; / p>

2)生成第二个图例,除了捕获数据中的值,还有ID_1中的条目及其标签列中的相应描述在数据框中。



我希望我明确提出了我的问题。



谢谢。 $ b

解决方案

首先,让我道歉,花费很长时间才能回来 - 我错过了所有其他人的评论。这是你想到的吗?





这是用以下代码生成的。在进行解释之前,您应该注意,创建图例是您的问题中最少的一个。请注意两个地图中的颜色不同。您上面的代码不会将CO2更改分配给正确的区域。例如,根据 MoroccoYields.csv ,最大的变化(改进?)是 -0.205 区域4 ,但在您的地图上,最大的(最黑的红色)位于摩洛哥东北部,实际上是 l'Oriental(第6区)

  ##加载包
库(rgdal)
库(plyr)
库(map)
库(maptools)
库(mapdata)
库(ggplot2)
库(RColorBrewer)
库(外部)
库(sp)

#get.centroids:从shapefile中提取多边形ID和质心的函数
get.centroids = function(x){
poly = MoroccoReg @ polygons [[x]]
ID = poly @ ID
centroid = as.numeric(poly @ labpt)
return(c(id = ID,long =质心[1],lat =质心[2])
}
#setwd(存储shapefile和yield的目录)
##加载shape文件和.csv文件
摩洛哥注册表(< - readOGR =。,layer =Morocco_adm1)
MoroccoYield< - read.csv(file =Morocco_Yield.csv,header = TRUE,sep =,,na.string =NA =。,strip.white = TRUE)
MoroccoYield $ ID_1< - substr(MoroccoYield $ ID_1,3,10)

##根据形状文件重新排序数据类别变量能够ID_1并更改为数据帧
摩洛哥指数< - 摩洛哥指数[订单(摩洛哥注册$ ID_1),]
摩洛哥Yield< - cbind(id = rownames(MoroccoReg @ data),MoroccoYield)
#建立注释标签表(图例)。
labs< - do.call(rbind,lapply(1:14,get.centroids))
labs< - merge(labs,MoroccoYield [,c(id,ID_1 label)],by =id)
labs [,2:3]< - sapply(labs [,2:3],function(x){as.numeric(as.character )})
labs $ sort< - as.numeric(as.character(labs $ ID_1))
labs< - labs [order(labs $ sort)]]

MoroccoReg.df< - fortify(MoroccoReg)
##这不工作...
##通过ID_1将.csv文件中的yield impact列添加到shapefile
##请注意,在.csv文件中,我刚刚添加了列ID_1,以将其与shapefile
#MoroccoReg.df< - cbind(MoroccoReg.df,MoroccoYield,by ='ID_1' )
##这样做...
MoroccoReg.df< - merge(MoroccoReg.df,MoroccoYield,by =id)

##检查shapefile的结构和内容
属性(MoroccoReg.df)
##绘制

摩洛哥地图1< - ggplot(data = MoroccoReg.df,aes(long,lat,group = id))
摩洛哥地图1< - 摩洛哥egMap1 + geom_polygon(aes(fill = A2Med_noCO2))
MoroccoRegMap1< - MoroccoRegMap1 + geom_path(color ='gray',linestyle = 2)
MoroccoRegMap1< - MoroccoRegMap1 + scale_fill_gradient2(name =%Change在yield中,low =#CC0000,mid =#FFFFFF,high =#006600)
摩洛哥注册地图1 - 摩洛哥注册地图1 +实验室(标题=SRES_A2,noCO2效应)
MoroccoRegMap1< - MoroccoRegMap1 + coord_equal()#+ theme_map()
MoroccoRegMap1< - MoroccoRegMap1 + geom_text(data = labs,aes(x = long,y = lat,label = ID_1),size = 4)
MoroccoRegMap1< - MoroccoRegMap1 + annotate(text,x = max(labs $ long)-5,y = min(labs $ lat)+ 3-0.5 *(1:14),
label = paste(实验室$ ID_1,:,labs $ Label,sep =),
size = 3,hjust = 0)
摩洛哥注册地图1
/ pre>

说明:



首先,将收益数据与地图区域:您使用

  Mor occoReg.df<  -  cbind(MoroccoReg.df,MoroccoYield,by ='ID_1')

不是如何 cbind(...)的作品。 cbind(...)仅将列的参数组合起来。它不是一个合并函数。所以你有一个数据框, MoroccoReg.df ,有107,800行(地图上的每一行端点都有一行),你将它与 MoroccoYield ,共有14行(每个区域为1)。所以 cbind(...)复制这14行7700次,以填写所需的107,800行。 by =ID_1的表达式仅仅添加了另一个名为的列,其中ID_1 复制107,800次。运行上面的语句,然后键入 head(MoroccoReg.df)并查找最后一列。



那么如何做合并?在 R 中有很多功能,这些功能应该使得这很容易,但是我无法让任何人工作。这是什么工作:



shapefile中的每个多边形都有一个ID。 shapefile数据部分中还有一个ID_1字段,但这些字段与不同且不相关。 [BTW:shapefile data部分中的 ID_1 字段以及中的 ID_1 csv 文件也是不同的:后者具有 c>TR前面的区域号;所以也要处理]。
使用以下格式重新排列shapefile:

  MoroccoReg<  -  MoroccoReg [order(MoroccoReg $ ID_1)]] 

将更改多边形的顺序,但不会更改其ID。事实证明,多边形ID与shapefile的数据部分中的行名称相匹配,所以我将(code> cbind(...)!)添加到 MoroccoYeild 数据框。

  MoroccoYield<  -  cbind(id = rownames @data),MoroccoYield)

所以现在 MoroccoYield 具有映射到多边形ID的 id 字段和标识区域的 ID_1 字段。现在我们可以 fortify(...) merge(...) merge(...)确实需要一个 by = 参数。



pre> MoroccoReg.df< - fortify(MoroccoReg)
MoroccoReg.df< - merge(MoroccoReg.df,MoroccoYield,by =id)

将所有 MoroccoYield 列追加到相应的行 MoroccoReg.df



创建图例:



明显的问题是如何定位标签?理想情况下,我们将把区域号从 MoroccoYield $ ID_1 放在每个区域的中心位置,然后根据创建一个标识区域的图例,摩洛哥Yield $ Label



那么在哪里找到重心?这些存储在shapefile的多边形部分中的模糊位置。为了简短说明,我创建了一个从多边形中提取质心的实用函数 get.centroid(...)。然后我将该函数应用于所有多边形,以生成具有相应多边形ID的质心表。然后我将它与 MoroccoYield 中的标签合并。这创建了一个数据框架 labs ,它具有以下列:

  id :多边形ID 
long:质心经度
纬度:质心纬度
ID_1:区域ID
标签:区域名称
排序:可排序(数字)版本的ID_1

然后,将以下代码添加到您的ggplot ...

  ... 
摩洛哥注册地图1 - 摩洛哥注册地图1 + geom_text(data = labs,aes(x = long,y = lat,label = label.id) size = 4)
MoroccoRegMap1< - MoroccoRegMap1 + annotate(text,x = max(labs $ long)-5,y = min(labs $ lat)+ 3-0.5 *(1:14)
label = paste(labs $ label.id,:,labs $ Label,sep =)
size = 3,hjust = 0)

...创建地图。没有干净的方法,我可以找到,用正式的ggplot传奇来做到这一点,所以我不得不使用 annotate(...)



编辑:为了回应@ smailov83的评论,如果你改变了这个注释代码创建ggplot到这个...

  MoroccoRegMap1<  -  ggplot(data = MoroccoReg.df,aes(long, lat,group = group)
MoroccoRegMap1< - MoroccoRegMap1 + geom_polygon(aes(fill = A2Med_noCO2))
MoroccoRegMap1< - MoroccoRegMap1 + geom_path(color ='gray',linestyle = 2)
MoroccoRegMap1< - MoroccoRegMap1 + scale_fill_gradient2(name =%Change in yield,low =#CC0000,mid =#FFFFFF,high =#006600)
摩洛哥注册地图1< - 摩洛哥注册地图1 + labs(title =SRES_A2,noCO2 Effect)
摩洛哥注册地图1< - 摩洛哥注册地图1 + coord_equal()#+ theme_map()
摩洛哥注册地图1< - 摩洛哥注册地图1 + geom_text(data = labs,aes(x = long ,y = lat,label = ID_1,group = ID_1),size = 4)
摩洛哥注册地图1 - 摩洛哥注册地图1 +注释(文本,x =最大(实验室长)-5,y = $ lat)+ 3-0.5 *(1:14),
label = paste(labs $ ID_1,:,labs $ Label,sep =),
size = 3,hjust = 0)

...你得到这个:





我相信修正了这个问题。您的地图中额外行的原因是 ggplot 必须按照 MoroccoReg.df $ group (所以, aes(...,group = group) aes(...,group = id) )。然而,当您执行此操作时, ggplot 尝试在所有图层中按group进行分组。在 geom_text(...)中,我们正在使用新的本地数据集 - 实验室数据框架 - 那里不是列。为了处理这个问题,我们必须在 geom_text(...)中明确设置 group 。底线:这似乎工作。


SpatialPoly Data: SpatialData

Yield Data: Yield Data

Code:

    ## Loading packages
    library(rgdal)
    library(plyr)
    library(maps)
    library(maptools)
    library(mapdata)
    library(ggplot2)
    library(RColorBrewer)
    library(foreign)  
    library(sp)

    ## Loading shapefiles and .csv files
    #Morocco <- readOGR(dsn=".", layer="Morocco_adm0")
    MoroccoReg <- readOGR(dsn=".", layer="Morocco_adm1")
    MoroccoYield <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/RMaps_Morocco/Morocco_Yield.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)

    ## Reorder the data in the shapefile based on the category variable "ID_1" and change to dataframe
    MoroccoReg <- MoroccoReg[order(MoroccoReg$ID_1), ]
    MoroccoReg.df <- fortify(MoroccoReg)

    ## Add the yield impacts column to shapefile from the .csv file by "ID_1"
    ## Note that in the .csv file, I just added the column "ID_1" to match it with the shapefile
    MoroccoReg.df <- cbind(MoroccoReg.df,MoroccoYield,by = 'ID_1')

    ## Check the structure and contents of shapefile
    attributes(MoroccoReg.df)

    ## Define new theme for map
    ## I have found this function on the website
    theme_map <- function (base_size = 12, base_family = "") {
    theme_gray(base_size = base_size, base_family = base_family) %+replace% 
    theme(
    axis.line=element_blank(),
    axis.text.x=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks=element_blank(),
    axis.ticks.length=unit(0.3, "lines"),
    axis.ticks.margin=unit(0.5, "lines"),
    axis.title.x=element_blank(),
    axis.title.y=element_blank(),
    legend.background=element_rect(fill="white", colour=NA),
    legend.key=element_rect(colour="white"),
    legend.key.size=unit(1.5, "lines"),
    legend.position="right",
    legend.text=element_text(size=rel(1.2)),
    legend.title=element_text(size=rel(1.4), face="bold", hjust=0),
    panel.background=element_blank(),
    panel.border=element_blank(),
    panel.grid.major=element_blank(),
    panel.grid.minor=element_blank(),
    panel.margin=unit(0, "lines"),
    plot.background=element_blank(),
    plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
    plot.title=element_text(size=rel(1.8), face="bold", hjust=0.5),
    strip.background=element_rect(fill="grey90", colour="grey50"),
    strip.text.x=element_text(size=rel(0.8)),
    strip.text.y=element_text(size=rel(0.8), angle=-90) 
    )   
    }

    ## Plotting 

    MoroccoRegMap1 <- ggplot(data = MoroccoReg.df, aes(long, lat, group = group)) 
    MoroccoRegMap1 <- MoroccoRegMap1 + geom_polygon(aes(fill = A2Med_noCO2))
    MoroccoRegMap1 <- MoroccoRegMap1 + geom_path(colour = 'gray', linestyle = 2)
    #MoroccoRegMap <- MoroccoRegMap + scale_fill_gradient(low = "#CC0000",high = "#006600")
    MoroccoRegMap1 <- MoroccoRegMap1 + scale_fill_gradient2(name = "%Change in yield",low = "#CC0000",mid = "#FFFFFF",high = "#006600")
    MoroccoRegMap1 <- MoroccoRegMap1 + labs(title="SRES_A2, noCO2 Effect")
    MoroccoRegMap1 <- MoroccoRegMap1 + coord_equal() + theme_map()
    MoroccoRegMap1

Results:

Question:

In Yield data, I have a column that describes the labels corresponding to each of the entries in the column "ID_1". What I am trying to achieve is two things:

1) plot the map and add the "ID_1" variable entries as labels on the map, thus identifying each region;

2) generate a second legend, besides the one that captures the values in the data, and which the entries in "ID_1" and their corresponding description in the "Labels" column in the dataframe.

I hope I framed my question clearly.

thanks.

解决方案

First, let me apologize for taking so long to get back - I missed your comment among all the others. Is this what you had in mind?

This was produced with the following code. Before getting into an explanation, you should be aware that creating a legend is the least of your problems. Note how the colors are different in the two maps. Your code above does not assign CO2 changes to the correct regions. For example, according to MoroccoYields.csv, the largest change (improvement?) was -0.205 in Region 4, but on your map the largest (darkest red) is at the northeastern tip of Morocco, which is actually l'Oriental (Region 6). An explanation follows the code.

## Loading packages
library(rgdal)
library(plyr)
library(maps)
library(maptools)
library(mapdata)
library(ggplot2)
library(RColorBrewer)
library(foreign)  
library(sp)

# get.centroids: function to extract polygon ID and centroid from shapefile
get.centroids = function(x){
  poly = MoroccoReg@polygons[[x]]
  ID   = poly@ID
  centroid = as.numeric(poly@labpt)
  return(c(id=ID, long=centroid[1], lat=centroid[2]))
}
#setwd("Directory where shapefile and Yields are stored")
## Loading shapefiles and .csv files
MoroccoReg        <- readOGR(dsn=".", layer="Morocco_adm1")
MoroccoYield      <- read.csv(file = "Morocco_Yield.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)
MoroccoYield$ID_1 <- substr(MoroccoYield$ID_1,3,10)

## Reorder the data in the shapefile based on the category variable "ID_1" and change to dataframe
MoroccoReg    <- MoroccoReg[order(MoroccoReg$ID_1), ]
MoroccoYield  <- cbind(id=rownames(MoroccoReg@data),MoroccoYield)
#  build table of labels for annotation (legend).
labs          <- do.call(rbind,lapply(1:14,get.centroids))
labs          <- merge(labs,MoroccoYield[,c("id","ID_1","Label")],by="id")
labs[,2:3]    <- sapply(labs[,2:3],function(x){as.numeric(as.character(x))})
labs$sort <- as.numeric(as.character(labs$ID_1))
labs          <- labs[order(labs$sort),]

MoroccoReg.df <- fortify(MoroccoReg)
## This does NOT work...
## Add the yield impacts column to shapefile from the .csv file by "ID_1"
## Note that in the .csv file, I just added the column "ID_1" to match it with the shapefile
#MoroccoReg.df <- cbind(MoroccoReg.df,MoroccoYield,by = 'ID_1')
## Do it this way...
MoroccoReg.df <- merge(MoroccoReg.df,MoroccoYield, by="id")

## Check the structure and contents of shapefile
attributes(MoroccoReg.df)
## Plotting 

MoroccoRegMap1 <- ggplot(data = MoroccoReg.df, aes(long, lat, group=id)) 
MoroccoRegMap1 <- MoroccoRegMap1 + geom_polygon(aes(fill = A2Med_noCO2))
MoroccoRegMap1 <- MoroccoRegMap1 + geom_path(colour = 'gray', linestyle = 2)
MoroccoRegMap1 <- MoroccoRegMap1 + scale_fill_gradient2(name = "%Change in yield",low = "#CC0000",mid = "#FFFFFF",high = "#006600")
MoroccoRegMap1 <- MoroccoRegMap1 + labs(title="SRES_A2, noCO2 Effect")
MoroccoRegMap1 <- MoroccoRegMap1 + coord_equal() #+ theme_map()
MoroccoRegMap1 <- MoroccoRegMap1 + geom_text(data=labs, aes(x=long, y=lat, label=ID_1), size=4)
MoroccoRegMap1 <- MoroccoRegMap1 + annotate("text", x=max(labs$long)-5, y=min(labs$lat)+3-0.5*(1:14),
                                            label=paste(labs$ID_1,": ",labs$Label,sep=""),
                                            size=3, hjust=0)
MoroccoRegMap1

Explanation:

First, on merging your yield data with the map regions: you use

MoroccoReg.df <- cbind(MoroccoReg.df,MoroccoYield,by = 'ID_1')

This is not how cbind(...) works. cbind(...) merely combines it's arguments column-wise. It is not a merge function. So you had a data frame, MoroccoReg.df, with 107,800 rows (one row for every line endpoint on your map), and you are combining it with MoroccoYield, which has 14 rows (1 for every Region). So cbind(...) replicates those 14 rows 7700 times to fill out the 107,800 rows it needs. The expression by="ID_1" merely adds another column named "by" with "ID_1" replicated 107,800 times. Run the statement above and type head(MoroccoReg.df) and look for the last column.

So how to do the merge? There are a number of functions in R that are supposed to make this easy, but I couldn't get any of them to work. This is what did work:

Every polygon in the shapefile has an ID. There is also an "ID_1" field in the shapefile data section, but these are different and unrelated. [BTW: The ID_1 field in the shapefile data section, and the ID_1 field in your csv file were also different: the latter has "TR" prepended to the region number; so that had to be dealt with as well]. Reordering the shapefile with:

MoroccoReg    <- MoroccoReg[order(MoroccoReg$ID_1), ]

will change the order of the polygons, but will not change their ID's. It turns out that the polygon ID matches the row name in the data section of the shapefile, so I prepended that (using cbind(...)!) to your MoroccoYeild data frame.

MoroccoYield  <- cbind(id=rownames(MoroccoReg@data),MoroccoYield)

So now MoroccoYield has an id field which maps to the polygon ID, and an ID_1 field, which identifies the Region. Now we can fortify(...) and merge(...). merge(...) does take a by= argument.

MoroccoReg.df <- fortify(MoroccoReg)
MoroccoReg.df <- merge(MoroccoReg.df,MoroccoYield, by="id")

This appends all of your MoroccoYield columns to the appropriate rows of MoroccoReg.df.

Creating the legend:

The obvious question is how to position the labels? Ideally, we would place the Region number from MoroccoYield$ID_1 at the centroid of each region, and then create a legend that identifies the Regions, based on MoroccoYield$Label.

So where to find the centroids? These are stored in an obscure location in the polygon section of the shapefile. To make a long story short, I created a utility function get.centroid(...) which extracts the centroid from a polygon. Then I applied that function to all the polygons to produce a table of centroids with corresponding polygon ID. Then I merged that with the labels in MoroccoYield. This created a data frame labs which has the following columns:

id:    polygon ID
long:  centroid longitude
lat:   centroid latitude
ID_1:  region ID
label: region name
sort:  a sortable (numeric) version of ID_1

Then, adding the following code to your ggplot...

...
MoroccoRegMap1 <- MoroccoRegMap1 + geom_text(data=labs, aes(x=long, y=lat, label=label.id), size=4)
MoroccoRegMap1 <- MoroccoRegMap1 + annotate("text", x=max(labs$long)-5, y=min(labs$lat)+3-0.5*(1:14),
                                            label=paste(labs$label.id,": ",labs$Label,sep=""),
                                            size=3, hjust=0)

...creates the map. There's no clean way, that I could find, to do this with a formal "ggplot legend", so I had to use annotate(...). Positioning the annotation is kind of a hack, but it seems to work.

Edit: In response to @smailov83's comment, if you change the code to create the ggplot to this...

MoroccoRegMap1 <- ggplot(data = MoroccoReg.df, aes(long, lat, group=group)) 
MoroccoRegMap1 <- MoroccoRegMap1 + geom_polygon(aes(fill = A2Med_noCO2))
MoroccoRegMap1 <- MoroccoRegMap1 + geom_path(colour = 'gray', linestyle = 2)
MoroccoRegMap1 <- MoroccoRegMap1 + scale_fill_gradient2(name = "%Change in yield",low = "#CC0000",mid = "#FFFFFF",high = "#006600")
MoroccoRegMap1 <- MoroccoRegMap1 + labs(title="SRES_A2, noCO2 Effect")
MoroccoRegMap1 <- MoroccoRegMap1 + coord_equal() #+ theme_map()
MoroccoRegMap1 <- MoroccoRegMap1 + geom_text(data=labs, aes(x=long, y=lat, label=ID_1, group=ID_1), size=4)
MoroccoRegMap1 <- MoroccoRegMap1 + annotate("text", x=max(labs$long)-5, y=min(labs$lat)+3-0.5*(1:14),
                                            label=paste(labs$ID_1,": ",labs$Label,sep=""),
                                            size=3, hjust=0)

...you get this:

Which I believe fixes the problem. The reason for the extra lines in your map was that the ggplot must be grouped by the column MoroccoReg.df$group (so, aes(..., group=group) not aes(...,group=id)). When you do this, however, ggplot tries to group by "group" in all layers. In geom_text(...), where we are using a new, local dataset - the labs data frame - there is no group column. To deal with this, we must explicitly set group to something else in geom_text(...). Bottom line: this seem to work.

这篇关于如何使用ggplot2使用描述关联标签的图例为区域地图添加图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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