代码之家  ›  专栏  ›  技术社区  ›  Danny David Leybzon

如何将IP转换为地址,然后按城市对这些地址进行分组?

  •  2
  • Danny David Leybzon  · 技术社区  · 9 年前

    我有一个由IP地址和相应值组成的数据帧。我想将这些IP地址(转换为地理空间坐标)和相应的值可视化为气泡图。

    问题是,其中一些IP地址位于同一城市。这意味着我在几乎完全相同的区域有多个气泡,我宁愿看到它们组合成一个气泡。

    到目前为止,我尝试的是转换IP地址->纬度和经度( ip2coordinates 从…起 RDSTK )->地址(使用 coordinates2politics 从…起 RDSTK公司 ),然后使用 CartoDB 将这些城市名称转换为坐标并在那里绘制。

    我已经跑了 coordinates <- lapply(ips$field_1, ip2coordinates) ,但它不是返回数据帧,而是返回一个很长(无用)的列表。

    做我想做的事情的另一种方式是什么?

    1 回复  |  直到 9 年前
        1
  •  3
  •   hrbrmstr    9 年前

    不需要笨重的DSTK:

    library(iptools)
    library(rgeolocate)
    library(dplyr)
    library(ggplot2)
    library(ggalt)
    
    URL <- "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz"
    fil <- basename(URL)
    if (!file.exists(fil)) download.file(URL, fil)
    R.utils::gunzip(fil, overwrite=TRUE)
    
    ips <- ip_random(10000)
    ip_geo <- maxmind(ips, "GeoLite2-City.mmdb", c("country_name", "city_name", "longitude", "latitude"))
    
    count(ip_geo, longitude, latitude, sort=TRUE) %>% 
      filter(!is.na(longitude)) -> for_circles
    
    world_map <- map_data("world")
    world_map <- filter(world_map, region != "Antarctica")
    
    gg <- ggplot()
    gg <- gg + geom_map(data=world_map, map=world_map,
                        aes(long, lat, map_id=region),
                        colour="#2b2b2b", size=0.15, fill=NA)
    gg <- gg + geom_point(data=for_circles, 
                          aes(x=longitude, y=latitude, size=n),
                          shape=21, stroke=0.15, alpha=1.8/2, color="#b2182b")
    gg <- gg + scale_size_continuous(trans="log10")
    gg <- gg + coord_proj("+proj=wintri")
    gg <- gg + ggthemes::theme_map()
    gg
    

    enter image description here

    或者,将它们装箱:

    pts <- hexbin(ip_geo$longitude, ip_geo$latitude, xbins=5)
    from_hex <- data_frame(x=pts@xcm, y=pts@ycm, n=pts@count)
    
    gg <- ggplot()
    gg <- gg + geom_map(data=world_map, map=world_map,
                        aes(long, lat, map_id=region),
                        colour="#2b2b2b", size=0.15, fill=NA)
    gg <- gg + geom_point(data=from_hex, aes(x, y, size=n),
                          shape=21, stroke=0.5, color="#b2182b", fill="#b2182b22")
    gg <- gg + scale_size_continuous(trans="sqrt")
    gg <- gg + coord_proj("+proj=wintri")
    gg <- gg + ggthemes::theme_map()
    gg
    

    enter image description here

    您还可以按地区(国家、州等)划分县,然后在每个地区的中心绘制圆。