我正在尝试使用ggplot2
以及映射包geom_sf
的新(和令人敬畏的)简单要素来绘制几个地理数据集。当我试图强制使用行类型的图例时,我会被传说和错误代码Error: length(rows) == 1 is not TRUE
(似乎属于ddply
)所愚弄功能显示为一行。
这是我调用的代码,它生成下面的图表;一切都很好除了传奇,其中Line1显示为一个方框/填充。
ggplot() +
geom_sf(data=sct, aes(fill=as.factor(sct$tc2)), color = "gray82") +
scale_fill_manual(values=c("white","goldenrod1","dodgerblue"),
labels = c("Omitted", "Control", "Treated"),
name = "Legend") +
geom_sf(data=lines1925All, aes(color="A"), linetype="dashed") +
scale_color_manual(values = c("A" = "olivedrab"),
labels = c("Line1"),
name = "what line?") +
theme_minimal() +
coord_sf(xlim=mapRange2[c(1:2)], ylim=mapRange2[c(3:4)])
这是图表:
现在,如果我尝试使用show.legend
(= TRUE
或= "line"
)强制图例看起来像一条线,请参阅下面的
geom_sf(data=lines1925All, aes(color="A"), linetype="dashed", show.legend = "line") +
我收到错误Error: length(rows) == 1 is not TRUE
。如果我单独绘制geom_sf
的任一个实例,我就不会收到任何错误,并且可以使用show.legend = "line"
使图例看起来正确。
注意:我没有包含一个可重复性最小的示例,因为我无法通过易于共享数据来复制它;见Add multiple legends to ggplot2 when using geom_sf。我已经尝试了几天找到答案,没有运气。
答案 0 :(得分:4)
我现在没有看到解决方案,但至少这是一个可重复性最小的例子 也许这是一个错误,那么最好的选择就是在github上发布一个问题。
library(sf)
#> Linking to GEOS 3.5.1, GDAL 2.1.3, proj.4 4.9.2, lwgeom 2.3.2 r15302
library(ggplot2)
# Create a ploygon object (with 3 polygons)
poly1 <- cbind(lon=c(5, 6, 7, 5),
lat=c(52, 53, 51, 52))
poly <- st_sf(st_sfc(list(st_polygon(list(poly1)),
st_polygon(list(poly1 - 1)),
st_polygon(list(poly1 + 1)))))
poly$treatment <- factor(c("Omitted", "Control", "Treated"))
# create two line objects
line1 <- st_sf(st_sfc(list(st_linestring(cbind(lon = c(5.5, 4.5), lat = c(53.5, 54.5))))))
line2 <- st_sf(st_sfc(list(st_linestring(cbind(lon = c(5, 7.5), lat = c(53, 52))))))
这有效:
ggplot() +
geom_sf(data= line1, aes(color="A"), show.legend = "line")
这也有效
ggplot() +
geom_sf(data= line1, aes(color="A"), show.legend = "line") +
geom_sf(data = poly)
这样可行,但我们希望颜色图例显示一行
ggplot() +
geom_sf(data= line1, aes(color="A")) +
geom_sf(data = poly, aes(fill = treatment))
这不起作用
ggplot() +
geom_sf(data= line1, aes(color="A"), show.legend = "line") +
geom_sf(data = poly, aes(fill = treatment))
#> Error: length(rows) == 1 n'est pas TRUE
Nb:color = "A"
在审美中的奇怪用法是因为
对于空间数据,我们通常拥有我们想要的不同空间数据集
设置美学,但我们也想要一个传奇(例如:蓝色的河流
和红色的道路)。
例如:
ggplot() +
geom_sf(data= line1, aes(color="A"), show.legend = "line") +
geom_sf(data= line2, aes(color="B"), show.legend = "line") +
geom_sf(data = poly) +
scale_color_manual(values = c("A" = "red", "B" = "blue"),
labels = c("Roads", "Rivers"),
name = "Linear \ncomponents")
由reprex package(v0.2.0)创建于2018-02-20。
答案 1 :(得分:1)
这是由于处理ggplot2
中缺失的美学,自从开发以来刚刚解决了。软件包版本2.2.1.9000
的版本:https://github.com/tidyverse/ggplot2/commit/4635bbb1e50d94e8d2017f084f75e2f709daeb18