如何将数据框中的信息添加到R中的美国地图上?

时间:2021-11-01 09:12:16

I have a data frame based on the global terrorism database called gtd in R.

我有一个基于全球*数据库的数据框,名为gtd in R.

I have the maps package downloaded/required

我已下载/需要地图包

What I am trying to do is take data from my gtd data frame and add the points on a US map.

我想要做的是从我的gtd数据框中获取数据并在美国地图上添加点。

I know the code for the USA map is map("state")

我知道美国地图的代码是地图(“州”)

in my gtd data frame, there is a column for latitude and longitude

在我的gtd数据框中,有一个纬度和经度列

all I want to do is plot the points on the US map to show location of where terrorist attacks happened in US

我想做的就是在美国地图上绘制点,以显示在美国发生恐怖袭击的位置

so from my gtd database to only get a subset where American longitude/latitude is needed I know I would use

所以从我的gtd数据库到只有一个子集,其中需要美国经度/纬度,我知道我会使用

subset(x=gtd, country_txt=="United States")

but from there, how to I plot the location of attacks as points on the USA map?

但是从那里开始,如何在美国地图上绘制攻击的位置?

Much appreciated!

非常感激!

1 个解决方案

#1


1  

I'm going to make the broad assumption from clues in your post that you're using data from the global terrorism database. If you've managed to read in the huge CSV from it, what you want to do should work and you're really close to having the answer. Basically, you just need to add the points() to the map():

我将从你的帖子中的线索中做出广泛的假设,即你正在使用来自全球*数据库的数据。如果你已经设法从中读取了巨大的CSV,那么你想要做的就应该工作,你真的很接近答案。基本上,您只需要将points()添加到map():

library(maps)

# assuming you have it in a CSV file
dat <- read.csv("gtd.csv")

# subset only points in the US
US <- dat[dat$country_txt == "United States",]

# plot the base US map
map('state')

# add points with really horrid default color, point type & size
# changing this is a good exercise for the poster :-)
points(x=US$longitude, y=US$latitude, col="red", cex=0.75)

如何将数据框中的信息添加到R中的美国地图上?

This has nothing to do with ggplot2 though, so consider removing that tag. It can be done with ggplot but maps() doesn't use it.

这与ggplot2无关,因此请考虑删除该标记。它可以用ggplot完成,但maps()不使用它。

#1


1  

I'm going to make the broad assumption from clues in your post that you're using data from the global terrorism database. If you've managed to read in the huge CSV from it, what you want to do should work and you're really close to having the answer. Basically, you just need to add the points() to the map():

我将从你的帖子中的线索中做出广泛的假设,即你正在使用来自全球*数据库的数据。如果你已经设法从中读取了巨大的CSV,那么你想要做的就应该工作,你真的很接近答案。基本上,您只需要将points()添加到map():

library(maps)

# assuming you have it in a CSV file
dat <- read.csv("gtd.csv")

# subset only points in the US
US <- dat[dat$country_txt == "United States",]

# plot the base US map
map('state')

# add points with really horrid default color, point type & size
# changing this is a good exercise for the poster :-)
points(x=US$longitude, y=US$latitude, col="red", cex=0.75)

如何将数据框中的信息添加到R中的美国地图上?

This has nothing to do with ggplot2 though, so consider removing that tag. It can be done with ggplot but maps() doesn't use it.

这与ggplot2无关,因此请考虑删除该标记。它可以用ggplot完成,但maps()不使用它。