【问题标题】:Add points ggplot添加点ggplot
【发布时间】:2014-05-27 10:45:50
【问题描述】:

嗨,我有很多这样的数据框

       id     oldid   yr mo dy    lon    lat
1  01206295 Aberfeldy 1885  3 22 -127.1 -31.78
2  05670001  05670005 1885  3 22  -4.38  49.15
3     06279     06279 1885  3 22 -123.5   37.5
4    106251     06323 1885  3 22  178.5   19.5
5 58FFF3618 58FFF3618 1885  3 22  -0.73  69.73
6 Achille.F Achille.F 1885  3 22 -35.62  -2.98

存储在不同的文件myfiles 中,我正在尝试使用根据 id 值选择的颜色为每个点绘制 (lon,lat) 点。到目前为止,我都是这样做的

for (i in 1:length(myfiles)){
      colnames(myfilesContent[[i]]) <-c("id","oldid","yr","mo","dy","lon","lat")
      p <- ggplot() + geom_polygon(data=world_map,aes(x=long, y=lat,group=group)) 
      myfilesContent[[i]]$lon <- as.numeric(myfilesContent[[i]]$lon)
      myfilesContent[[i]]$lat <- as.numeric(myfilesContent[[i]]$lat) 
      p + geom_point(data=myfilesContent[[i]], aes(x=lon, y=lat, fill=as.factor(id)), size = 4, shape = 21, show_guide=FALSE)
      print(p)
}

无论如何,我不确定如果一个 id 在不同的文件中,它将被分配相同的颜色

非常感谢

【问题讨论】:

  • 这取决于你如何分割数据框。如果您将其按id 拆分(就像我在previous answer 中对您的问题所做的那样),那么您应该没有问题。
  • 嗨,谢谢,但我的文件不是按 id 而是按日期拆分的……我必须做两个 for 循环吗?
  • myfiles 包含每个日期的原始数据帧..

标签: r ggplot2


【解决方案1】:

您可以确保所有 id 列的级别都相同。首先,从所有data.frames 中获取所有ID 的主列表

allids <- unique(unlist(lapply(myfilesContent, function(x) levels(x[,1])))

然后确保所有 ID 列共享这些级别

lapply(seq_along(myfilesContent), function(i) {
    myfilesContent[[i]][,1] < -factor(myfilesContent[[i]][,1], levels=allids)
})

如果他们有相同的级别,他们应该得到相同的颜色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2021-09-13
    • 2018-09-04
    相关资源
    最近更新 更多