我有一个名为Completed的数据框,看起来像这样:
X1 Latitude Longitude Conservation
1 40 -8 Yes
2 -5 10 No
3 20 30 Yes
4 5 -10 No
我想生成一个非常简单的图,其中根据Conservation = Yes或No对世界地图上的点进行颜色编码。这是我尝试的代码:
world <- map_data("world")
gg1 <- ggplot() + geom_polygon(data = world, aes(x=long, y = lat, group = group)) +
coord_fixed(1.3)
labs <- data.frame(
long = Completed$Longitude,
lat = Completed$Latitude,
stringsAsFactors = FALSE
)
ID.list <- unique(Completed$X1)
for (X1 in ID.list) {
ifelse(Completed$Conservation %in% 'Yes', gg1 +
geom_point(data = labs, aes(x = long, y = lat), color = "yellow", size = 2), gg1 +
geom_point(data = labs, aes(x = long, y = lat), color = "pink", size = 2))
}
这会产生错误:“较长的对象长度不是较短的对象长度的倍数”
我对R很陌生,所以我很难理解这个问题的含义以及如何修复我的代码。感谢您的帮助!
答案 0 :(得分:0)
简短的答案:使用aes(color = Conservation)
而不是for
循环。
完整解决方案:
Completed <- tribble(
~X1, ~Latitude, ~Longitude, ~Conservation,
1, 40, -8, "Yes",
2, -5, 10, "No",
3, 20, 30, "Yes",
4, 5, -10, "No"
)
world <- map_data("world")
gg1 <- ggplot() + geom_polygon(data = world, aes(x=long, y = lat, group = group)) +
coord_fixed(1.3)
gg1 +
geom_point(aes(x = Longitude, y = Latitude, color = Conservation),
data = Completed, size = 2) +
scale_color_manual(values = c("pink", "yellow"))