在北卡罗来纳州的县建立一个衡量暴力犯罪的等值线

时间:2017-11-27 01:09:19

标签: r ggplot2 plotly choropleth

我想想象北卡罗来纳州的暴力犯罪

我的数据集看起来有点像这样:

次区域violent_crime

alamance    396.39

alexander   130.38

alleghany   137.48

anson   513.65

ashe    78.32

avery   138.51

beaufort    328.74

...

这是我的代码 - 到目前为止,只有北卡罗来纳州及其郡线的地图可视化。

我试图只使用ggplot和地图,但我遇到了死胡同

...

library(plotly)

library(ggplot2)

library(maps)

library(dplyr)

crime.df <- read.csv(file="B:/Data/visualization/violent_crimes.csv", header=TRUE, sep=",")


vcdExtra::datasets


nc <- subset(states, region == "north carolina")

head(nc)

counties <- map_data("county")

nc_county <- subset(counties, region == "north carolina")

head(nc_county)


choropleth <- inner_join(nc_county, crime.df, by = "subregion")

choropleth <- chloropleth[!duplicated(chloropleth$order),]

ggplot(data = nc, mapping = aes(x = long, y = lat, group = group)) + 

  coord_fixed(1.2) +

  geom_polygon(color = "black", fill = "gray") + 

  geom_polygon(data = nc_county, fill = NA, color = "white") +

  geom_polygon(color = "black", fill = NA)




...

谢谢!

1 个答案:

答案 0 :(得分:1)

library(ggplot2)
library(dplyr)

# Get NC counties

nc_map <- tbl_df(map_data("county", region = "north carolina"))

# Simulate data since you didn't use dput() as the R section of SO instructs you to do

set.seed(1492)
data_frame(
  subregion = unique(nc_map$subregion),
  crime = sample(50:500, length(unique(nc_map$subregion)))
) -> crime_df

# Join the values to the map

nc_map <- left_join(nc_map, crime_df)

# Plot it

ggplot() +
  geom_polygon(data=nc_map, color="black",
               aes(x=long, y=lat, group=subregion, fill=crime)) +
  viridis::scale_fill_viridis(name="Crime ", direction=-1) +
  coord_map("polyconic") +
  ggthemes::theme_map() +
  theme(legend.position="bottom")

enter image description here

考虑:

  • 将犯罪数据分成~5组
  • 确保您使用的是人均信息(因为您专注于NC,因此根据县人口数量)
  • 使用dput()作为SO R部分指示您可以包含数据
  • 尝试隔离错误并提供更好的错误说明
  • 阅读投影并尝试将ggalt::coord_proj()与此PROJ.4字符串一起使用:+proj=aea +lat_1=34.0207760236743 +lat_2=36.37811477607033 +lon_0=-80.716552734375与我的懒惰出路示例。