[R] Choropleth: Turnover by ZipCode

G.Maubach at weinwolf.de G.Maubach at weinwolf.de
Mon Jul 11 15:08:01 CEST 2016


Hi All,
Dear Readers,

I need to create a choropleth graph with turnover by zipcode. This is what 
I have so far:

# Not run (Begin)
# Install packages if needed
# install.packages(pkgs = c("maptools", "rgdal", "RColorBrewer", 
"grDevices"))
# Not run (End)

# Load libraries
library(maptools); library(rgdal); library(RColorBrewer); 
library(grDevices)

# Configuration
# Adjust if needed!
file_path <- file.path("C:", "temp")

# Read data 
# Source: http://arnulf.us/PLZ
url <- "http://www.metaspatial.net/download/plz.tar.gz"
file_name_gzip <- basename(url)
file_name_extract <- "post_pl.shp"

download.file(url, file.path(file_path, file_name_gzip))

untar(tarfile = file.path(file_path, file_name_gzip),
      compressed = "gzip",
      exdir = file_path)

# Dataset
# I have the data for all zipcodes available in my region
ds_temp <-
  structure(
    list(
      ZipCode = c(1099, 10178, 13125, 21406, 32429, 41569),
      Sales = c(4, 2, 9, 5, 7, 3),
      Revenue = c(12, 9, 100, 80, 90,
                  25)
    ),
    .Names = c("ZipCode", "Sales", "Revenue"),
    row.names = c(NA,
                  6L),
    class = "data.frame"
  )
print(ds_temp)

# Prepare graphic
file_name_pdf <- file.path(file_path, "sales-and-revenue-by-zipcodes.pdf")
cairo_pdf(bg = "grey98", file_name_pdf, width = 16, height = 9)

y <- readShapeSpatial(file.path(file_path, file_name_extract),
                      proj4string = CRS("+proj=longlat"))
x <- spTransform(y,CRS=CRS("+proj=merc"))

# How do I need to change this line?
# Needs to be replaced by turnover from ds_temp
color <- sample(1:7, length(x), replace=T) 

# Create graphic
plot(x, 
     col = brewer.pal(7, "Oranges")[color],
     border = F)  # How to I tell R to plot turnover from ds_temp?

# Title
mtext(
  "Turnover by Zipcodes",
  side = 3,
  line = -4,
  adj = 0,
  cex = 1.7
)

# Write to disc
dev.off()

# Cleanup
rm("ds_temp", "color", "file_name_extract",
   "file_name_gzip", "file_name_pdf", "file_path",
   "url", "x", "y")
unlink(file.path(file_path, "plz.tar.gz"))
unlink(file.path(file_path, "post_pl.dbf"))
unlink(file.path(file_path, "post_pl.shp"))
unlink(file.path(file_path, "post_pl.shx"))

# unlink(file.path(file_path, "sales-and-revenue-by-zipcodes.pdf"))

What do I need to do to color the amount of turnover or the frequencies of 
sales from the ds_temp dataset in the graph?

Kind regards

Georg Maubach



More information about the R-help mailing list