我有一个来自ggplot2的类CoordCartesian的ggproto对象。 我用下面的行创建了它;
Africablock<- list(coord_cartesian(xlim=c(-20,60), ylim=c(-38,25)))
我用它在一个较大地图的区域上绘制一个矩形,如下所示,我已经明确指定了y和x的最大值和最小值。
这是创建地图边界的代码:
mapWorld <- borders("world", colour="gray50", fill="grey90")
这是情节的代码:
mp <- NULL
mp <- ggplot(data=data, aes(x=as.numeric(DDEjitter1), y=as.numeric(DDSjitter1))) +
mapWorld +
Africablock +
geom_point( size=2, alpha = 0.7) +
coord_fixed(ratio = 1) +
geom_rect(aes(xmin=-20,
xmax=60,
ymin=-38,
ymax=25),
fill='transparent',
col='black',
size=0.1)
我想知道是否可以直接使用Africablock
对象来创建矩形。
我有几个这样的对象,我想把它们放在一个列表对象中,用于几个地图。
这里有一些dummie数据:
data<-data.frame(DDEjitter1={runif(min = -180,max = 180,n=200)},DDSjitter1={runif(min = -90,max = 90,n=200)},id=1:200)
答案 0 :(得分:1)
You can write a simple function that extracts the limits from a CoordCartesian
object, and uses them to construct a geom_rect
object that you can use in the plot:
library(ggplot2)
rect_from_coord <- function(coord, ...) {
geom_rect(
mapping = aes_(
xmin = coord$limits$x[1],
xmax = coord$limits$x[2],
ymin = coord$limits$y[1],
ymax = coord$limits$y[2]
),
...
)
}
coord <- coord_cartesian(xlim = c(2, 4), ylim = c(15, 25))
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
rect_from_coord(coord, fill = 'transparent', col = 'black', size = 0.1)
Created on 2018-03-09 by the reprex package (v0.2.0).