根据值设置点的颜色

时间:2018-01-11 21:05:49

标签: r ggplot2 coordinates conditional-statements ggmap

我有一个如下所示的数据框:

x1= c("Station 1", "Station 2", "Station 3", "Station 4", "Station 5", "Station 6")
x2= c(58.73, 57.20, 41.90, 38.00, 47.10, 67.30)
x3= c(16.55, -2.10, 8.80, 23.70, 24.50, 14.40)
x4= c(342, 1900, 283, 832, 212, 1533)
x5= c("rual", "rual", "urban", "suburban", "rual", "urban")

testframe = data.frame(Station=x1, LAT=x2, LON=x3, ALT=x4, AREA=x5) 

我想用3种不同的颜色显示点。绿色为rual,黄色为郊区,红色为都市。

但直到现在我才设法用一种颜色显示它们。我没有这个:

library(ggmap)
library(ggplot2)

Europe = get_map(location = "Europe", zoom = 4)

p = ggmap(Europe)
p = p + geom_point(data=testframe, aes(x=testframe$LON, y=testframe$LAT), color = "red", size=1)
p

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:3)

您可以尝试以下方法:

p +
  geom_point(data = testframe, aes(LON, LAT, color = AREA), size = 10) +
  scale_color_manual(name = "AREA", values = cols)

enter image description here

或者复制/粘贴这段代码:

library(ggmap)
library(ggplot2)

x1 <- c("Station 1", "Station 2", "Station 3", "Station 4", "Station 5", "Station 6")
x2 <- c(58.73, 57.20, 41.90, 38.00, 47.10, 67.30)
x3 <- c(16.55, -2.10, 8.80, 23.70, 24.50, 14.40)
x4 <- c(342, 1900, 283, 832, 212, 1533)
x5 <- c("rual", "rual", "urban", "suburban", "rual", "urban")

testframe <- data.frame(
  Station = x1,
  LAT = x2,
  LON = x3,
  ALT = x4,
  AREA = x5
)

Europe <- get_map(location = "Europe", zoom = 4)

cols <- c(
  "rual" = "darkgreen",
  "suburban" = "yellow",
  "urban" = "red"
)

p <- ggmap(Europe)

p +
  geom_point(data = testframe, aes(LON, LAT, color = AREA), size = 10) +
  scale_color_manual(name = "AREA", values = cols)