【发布时间】:2017-12-28 14:26:53
【问题描述】:
受this 帖子的启发,我尝试使用 Robinson 投影绘制世界地图,并在地图上添加彩色点。 重新投影地图和点可以正常工作,但是由于某种我不明白的原因,我无法更改点的配色方案并保留图例。我尝试了以下方法:
首先我在这里获得了形状文件:land 和 graticules
library(rgdal)
library(ggplot2)
library(sp)
library(yarrr)
setwd('~/Documents/worldshapefiles') # this is where the shapefiles are
# read the shapefile for the simple worldmap
wmap <- readOGR(dsn = 'ne_110m_land', layer = 'ne_110m_land')
wmap_df <- fortify(wmap)
# get bounding box
bbox <- readOGR("ne_110m_graticules_all", layer="ne_110m_wgs84_bounding_box") # read bounding box
bbox_df<- fortify(bbox)
site_locs <- cbind.data.frame(x = c(-5, -3, -3, 58, -112), y = c(68, -37, 35, 19, -4), ocean = c('NAT', 'IND', 'MDX', 'SAT', 'PAC'))
coordinates(site_locs) <- c("x", "y") # convert to spatialpointsdataframe
proj4string(site_locs) <- CRS("+proj=longlat + datum=WGS84")
# reproject everything
bbox_robin <- spTransform(bbox, CRS("+proj=robin"))
bbox_robin_df <- fortify(bbox_robin)
wmap_robin <- spTransform(wmap, CRS("+proj=robin"))
wmap_df_robin <- fortify(wmap_robin)
site_locs_robin <- spTransform(site_locs, CRS('+proj=robin'))
site_locs_robin_df <- as.data.frame(site_locs_robin)
col_pal <- piratepal('espresso', length.out = 5)
# plot
ggplot(bbox_robin_df, aes(long,lat)) +
geom_polygon(data = wmap_df_robin, aes(long,lat, group = group, fill = hole)) +
geom_point(data = site_locs_robin_df, aes(x, y, colour = ocean)) +
coord_equal() +
geom_polygon(linetype = 'solid', fill = NA, colour = 'black', size = 0.5) +
scale_fill_manual(values=c("black", "white"), guide="none")
但是,当我尝试更改色阶时:
ggplot(bbox_robin_df, aes(long,lat)) +
geom_polygon(data = wmap_df_robin, aes(long,lat, group = group, fill = hole)) +
geom_point(data = site_locs_robin_df, aes(x, y, colour = ocean)) +
scale_colour_manual(values = col_pal) +
coord_equal() +
geom_polygon(linetype = 'solid', fill = NA, colour = 'black', size = 0.5) +
scale_fill_manual(values=c("grey80", "white"), guide="none")
我收到以下警告 Removed 5 rows containing missing values (geom_point). 和一个空图。
当我像这样改变色标时:
ggplot(bbox_robin_df, aes(long,lat)) +
geom_polygon(data = wmap_df_robin, aes(long,lat, group = group, fill = hole)) +
geom_point(data = site_locs_robin_df, aes(x, y, colour = ocean), colour = col_pal) +
scale_colour_manual(values = col_pal) +
coord_equal() +
geom_polygon(linetype = 'solid', fill = NA, colour = 'black', size = 0.5) +
scale_fill_manual(values=c("grey80", "white"), guide="none")
颜色结果很好(在 col_pal 中指定),但我丢失了图例。
任何想法如何解决这个问题?还是其他方法?
实际上我还有更多的点,其中一些重叠,我想修正它们的绘制顺序(例如 SAT 在 IND 之上)。我该怎么做?
【问题讨论】:
-
您需要使用
scale_color_manual(values=col_pal)更改调色板而不更改代码中的任何其他内容。 -
@ClausWilke 谢谢,但我已经尝试过了,但收到警告“删除了 5 行包含缺失值 (geom_point)。”这导致一个空的情节
-
为了让任何人都有机会弄清楚发生了什么,您必须提供您编写的无效代码以及您的 shapefile。例如,您可以将它们作为要点上传。 gist.github.com
-
@ClausWilke 道歉,我编辑了这个问题。感谢您的帮助
-
我修复了色标问题。点顺序应该作为一个单独的问题提出,我建议您将其归结为minimal example.
标签: r ggplot2 map-projections