I'm making world maps with the rworldmap
package. I'm using a function to access trade data from UN Comtrade.
I edited my original question so I can show a real example of what I'm doing. Here is a map that I could make:
Function
library(rjson)
library(rworldmap)
get.Comtrade <- function(url="http://comtrade.un.org/api/get?", maxrec=50000,
type="C", freq="A", px="HS", ps="now", r, p, rg="all",
cc="TOTAL", fmt="json") {
string <- paste(url
, "max=", maxrec,"&" # maximum no. of records returned
, "type=", type, "&" # type of trade (c=commodities)
, "freq=", freq, "&" # frequency
, "px=", px, "&" # classification
, "ps=", ps, "&" # time period
, "r=", r, "&" # reporting area
, "p=", p, "&" # partner country
, "rg=", rg, "&" # trade flow
, "cc=", cc, "&" # classification code
, "fmt=", fmt # Format
, sep="")
if (fmt == "csv") {
raw.data <- read.csv(string,header=TRUE)
return(list(validation=NULL, data=raw.data))
} else {
if (fmt == "json" ) {
raw.data <- fromJSON(file=string)
data <- raw.data$dataset
validation <- unlist(raw.data$validation, recursive=TRUE)
ndata <- NULL
if (length(data) > 0) {
var.names <- names(data[[1]])
data <- as.data.frame(t(sapply(data,rbind)))
ndata <- NULL
for (i in 1:ncol(data)) {
data[sapply(data[, i], is.null), i] <- NA
ndata <- cbind(ndata, unlist(data[, i]))
}
ndata <- as.data.frame(ndata)
colnames(ndata) <- var.names
}
return(list(validation=validation, data=ndata))
}
}
}
Usage
dt2 <- get.Comtrade(r=32, p="all", rg=1, fmt="csv")
dt2df <- as.data.frame(do.call(rbind, dt2))
total <- sum(dt2df$Trade.Value..US..)
dt2df$p <- 100*dt2df$Trade.Value..US../total
dt2df <- dt2df[order(-dt2df[, "p"]), ]
top3 <- dt2df[4, "p"]
top10 <- dt2df[11, "p"]
q3 <- dt2df[as.integer(1*nrow(dt2df)/4), "p"]
q2 <- dt2df[as.integer(2*nrow(dt2df)/4), "p"]
q1 <- dt2df[as.integer(3*nrow(dt2df)/4), "p"]
mapped_data <- joinCountryData2Map(dt2df, joinCode="ISO3",
nameJoinColumn="Partner.ISO")
mapCountryData(mapped_data, nameColumnToPlot="p", numCats=6,
catMethod=c(0, q1, q2, q3, top10, top3, 100),
colourPalette=c('cornsilk', 'cornsilk2', 'palegreen1',
'palegreen2', 'palegreen4', 'darkgreen'),
mapTitle="", addLegend=FALSE)
The result is the map that I'm looking for, except that I don't need to see the Antarctica. How can I remove it?
I tried with xlim
& ylim
, but it didn't work.
Try
new_world <- subset(mapped_data, continent != "Antarctica")
after
mapped_data <- joinCountryData2Map(dt2df, joinCode = "ISO3", nameJoinColumn = "Partner.ISO")
then continue
mapCountryData(new_world, nameColumnToPlot = "p", numCats=6, catMethod =
c(0,q1,q2,q3,top10,top3,100), colourPalette = c('cornsilk','cornsilk2','palegreen1','palegreen2','palegreen4','darkgreen'), mapTitle="", addLegend=FALSE)