我在使用栅格数据(来自ggplot2 geom_tile)覆盖地图(来自地图包)时遇到问题?
library(ggplot2)
library(ggmap)
library(maps)
library(mapdata)
这是我的数据
mydata = read.csv("Seasonal_Temp.csv")
head(mydata)
> head(mydata)
longitude latitude seasonalTavg_Ens
1 -111.688 40.500 3.435
2 -111.688 40.563 3.183
3 -111.688 40.625 3.488
4 -111.625 40.500 3.437
5 -111.625 40.563 3.395
6 -111.625 40.625 3.429
这是地图
states <- map_data("state")
dim(states)
ut_df <- subset(states, region == "utah")
head(ut_df)
counties <- map_data("county")
ut_county <- subset(counties, region == "utah")
head(ut_county)
area <- subset(ut_county, subregion %in% c("summit", "wasatch", "salt lake",
"utah"))
area_map <- ggplot(data = area, mapping = aes(x = long, y = lat, group =
group)) +
coord_fixed(1.3) +
geom_polygon(color = "black", fill = "white")
area_map + theme_bw()
area_map + coord_fixed(xlim = c(-111.438, -111.688), ylim = c(40.5, 40.625),
ratio = 1.3)
我无法将我的栅格数据与地图合并..
ggplot() + geom_raster(data = mydata, aes(longitude,latitude, fill =
seasonalTavg_Ens))
感谢您的任何见解!我愿意使用geom_raster或geom_tile。
答案 0 :(得分:0)
制作ggplot并将其保存到对象时:
area_map <- ggplot(data = area, mapping = aes(x = long, y = lat, group = group)) +
coord_fixed(1.3) +
geom_polygon(color = "black", fill = "white")
并希望添加更多图层,这些图层将保存到您需要明确说明的同一对象
area_map <- area_map +
theme_bw() +
coord_fixed(xlim = c(-111.438, -111.688),
ylim = c(40.5, 40.625), atio = 1.3)
添加geom_tile图层:
area_map + geom_raster(data = mydata, aes(longitude, latitude,
fill = seasonalTavg_Ens), inherit.aes = F, alpha = 0.5)
另一个关键概念是使用特定数据在层中指定inherit.aes = F
,如果您在ggplot调用中定义了aes。因为在大多数情况下它不适用于具有特定数据的图层:
结果:
要匹配可以做的传奇
area_map + geom_raster(data = mydata,
aes(longitude,latitude,
fill = seasonalTavg_Ens),
inherit.aes = F,
alpha = 0.5) +
guides(fill = guide_legend(override.aes = list(alpha = 0.5)))
导致传奇看起来不连续。解决这个问题的一种方法是指定geom_path而不是geom_polygon,并完全避免使用alpha:
ggplot() +
geom_raster(data = mydata,
aes(longitude,latitude,
fill = seasonalTavg_Ens)) +
geom_path(data = area, aes(x = long, y = lat, group = group),
color = "black")+
coord_fixed(xlim = c(-111.438, -111.688), ylim = c(40.5, 40.625),
ratio = 1.3)+
theme_bw()