don*_*zao 16 r spatial shapefile ggplot2
很抱歉没有包含我的问题的任何示例数据.我找不到轻松生成示例形状文件的方法.希望有经验的用户ggplot
可以从下面的描述中看到我想做的事情.
我有:
一个data.frame
X与约样地信息(plotid
,var1
,var2
,var3
,var4
,...)
Y
具有样本图的空间信息的多边形shapefile
导入shapefile Y
(with maptools
)和fortify
ing as data.frame
Z
(ggplot2
)可以正常工作.melt
荷兰国际集团X
以X_melted
作品同样精致.merge
-ing Z
并X_melted
以mapdf
作品为好.
这意味着,现在我们有一个data.frame
长形式的空间信息和var1
,var2
,var3
,...
现在我想绘制这样的数据框:
pl1 <- ggplot(mapdf,aes(long,lat),group=group)
pl1 <- pl1 + geom_polygon(aes(group=group,fill=value),colour="black")
pl1 <- pl1 + facet_grid(variable ~ .)
pl1 <- pl1 + coord_equal(ratio = 1)
pl1
Run Code Online (Sandbox Code Playgroud)
结果是一个很好的情节,每个变量有一个面板.面板的地图是相同的,但填充颜色随变量的值而变化.到目前为止,一切都像魅力......有一个问题:
变量具有不同的最小值和最大值.例如var1
去从0
到5
,var2
从0
到400
,var3
从5
到10
,等等.在该示例中,对于填充颜色的传说从0
到400
.var2
是很好的绘制,但var1
和var3
基本相同的颜色.
有没有办法可以为刻面的每个面板使用不同的图例?或者这是不是(还)可能与facet_wrap
或facet_grid
在ggplot
?
我可以为每个变量制作单独的图并将它们与视口连接,但是有很多变量,这将是很多工作.
或者是否可以使用另一种方法或方法来完成我想做的事情?
非常感谢帮助.:)
编辑:在ggplot2
-package描述的帮助下,我构建了一个示例来说明我的问题:
ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))
values <- data.frame(
id = ids,
val1 = cumsum(runif(6, max = 0.5)),
val2 = cumsum(runif(6, max = 50))
)
positions <- data.frame(
id = rep(ids, each = 4),
x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)
values <- melt(values)
datapoly <- merge(values, positions, by=c("id"))
p <- ggplot(datapoly, aes(x=x, y=y)) + geom_polygon(aes(fill=value, group=id),colour="black")
p <- p + facet_wrap(~ variable)
p
Run Code Online (Sandbox Code Playgroud)
右侧的面板说明var2
了地图上的不同值.但是,在左侧面板上,所有多边形都具有相同的颜色.这是合乎逻辑的,因为所有面板只使用一种颜色渐变.我可以为每个面板使用不同的颜色渐变吗?
十多年后重新审视这个问题,优秀的ggnewscale
封装解决了多色标的问题。需要注意的是,您的方面数据需要两个单独的层,因此您必须将其稍微分解。将新比例添加到绘图中的顺序很重要,因此我建议使用“图层 - 比例 - new_scale - 图层 - 比例”的顺序。后续的新比例应重复“new_scale - 层 - 比例”模式。
library(ggplot2)
library(ggnewscale)
ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))
values <- data.frame(
id = ids,
val1 = cumsum(runif(6, max = 0.5)),
val2 = cumsum(runif(6, max = 50))
)
positions <- data.frame(
id = rep(ids, each = 4),
x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)
values <- reshape2::melt(values)
#> Using id as id variables
datapoly <- merge(values, positions, by=c("id"))
ggplot(datapoly, aes(x=x, y=y)) +
geom_polygon(aes(fill=value, group=id),
data = ~ subset(., variable == "val1"),
colour="black") +
scale_fill_distiller(palette = "Reds") +
new_scale_fill() +
geom_polygon(aes(fill=value, group=id),
data = ~ subset(., variable == "val2"),
colour="black") +
scale_fill_distiller(palette = "Greens") +
facet_wrap(~ variable)
Run Code Online (Sandbox Code Playgroud)
由reprex 包于 2021 年 2 月 12 日创建(v1.0.0)