添加点ggplot [英] Add points ggplot

查看:219
本文介绍了添加点ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我有很多像这样的数据框

  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)点。到目前为止,我正在这样做

pre $ for(i in 1:length(myfiles)){
colnames(myfilesContent [^])< -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列的级别相同。首先,从所有 data.frame s

中获取所有ID的主列表。

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

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

$ $ p $ lt; code> lapply(seq_along(myfilesContent),函数(i){
myfilesContent [[i]] [,1]< -factor(myfilesContent [[i]] [,1],levels = allids)
})

如果它们具有相同的级别,则它们应该具有相同的颜色。


Hi I have many data frame like this

       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

stored in different files myfiles and I am trying to plot the (lon,lat) points for each of them with the colour chosen according to the id value. So far I am doing like this

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)
}

Anyway I am not sure that if an id is in different files it will be assigned with the same colour

Many thanks

解决方案

You can make sure the levels for all your id columns are the same. First, get a master list of all the IDs from all the data.frames

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

Then make sure all the ID columns share these levels

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

If they have the same levels, they should get the same colors.

这篇关于添加点ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆