Ploting Countries in R Maps Library : Gray boundaries with FILL=TRUE - r

I am trying to plot countries in R Maps. However, when I use FILL=TRUE all my countries boundaries are drawn in black. I want them in Gray. This is my code:
library(maps) # Provides functions that let us plot the maps
library(mapdata) # Contains the hi-resolution points that mark out the Cnt
countries=c("Argentina","Armenia","Australia","Bahrain","Belgium","Botswana","Bulgaria","Canada", "Chile","Tawain", "Croatia","Cyprus", "Czech Republic", "Denmark","Egypt","UK:Great Britain","Finland", "France", "Georgia", "Germany", "China:Hong Kong", "Hungary", "Indonesia", "Iran", "Ireland", "Israel", "Italy", "Japan", "Jordan", "Kazakhstan", "Korea", "Kuwait", "Lebanon", "Lithuania", "Malaysia", "Malta", "Morocco", "Netherlands", "New Zealand", "UK:Northern Ireland", "Norway", "Oman", "Palestine", "Poland", "Portugal", "Qatar", "Russia", "Saudi Arabia", "Serbia", "Singapore", "Slovak Republic", "Slovenia", "South Africa", "Spain", "Sweden", "Thailand", "Turkey", "United Arab Emirates", "USA")
map('world', resolution=1, col="darkgray")
map('world', countries, resolution=1, fill = T, col = "royalblue", add = T)
map('world', resolution=1,col="darkgray", add=TRUE)
Any ideas will be appreciated.
Thanks
Jº

To change the colour of the boundaries, add the argument border='darkgrey'. This argument is not listed explicitely in the man page for 'map' because it is in fact an argument for the call to 'polygon'. It is mentioned in the '...' segment of the man page, though.
map('world', countries, resolution=1, fill = T,
col = "royalblue", border="darkgrey", add = T)

Related

How to bring a chord diagram to a similar form?

I have a database.
I want to build a chord diagram similar to this one:
https://i.stack.imgur.com/59JcJ.png
My code:
vertices <- data.frame(name = unique(c(as.character(imports$Partner), as.character(imports$Reporter))) )
mygraph <- graph_from_data_frame( imports, vertices=vertices )
from <- match( imports$Reporter, vertices$name)
to <- match( imports$Partner, vertices$name)
ggraph(mygraph, layout = 'dendrogram', circular = TRUE)
geom_conn_bundle(data = get_con(from = from, to = to), alpha=0.2, colour="skyblue", tension = 0)
geom_node_point(aes(filter = leaf, x = x*1.05, y=y*1.05))
theme_void()
Result:
https://i.stack.imgur.com/uY2Yq.png
I searched for all kinds of settings for the chord diagram, but I didn’t find, how to make the links of the same size, and set the number of lines as an indicator of the value. Does anyone know how to create such a diagram?
data=structure(list(Reporter = c("USA", "USA", "USA", "USA", "India",
"Japan", "Japan", "USA", "Rep. of Korea", "USA", "Japan", "Japan",
"Japan", "Rep. of Korea", "USA", "USA", "USA", "China", "USA",
"USA", "Rep. of Korea", "USA", "Japan", "Japan", "Rep. of Korea",
"China", "China", "Rep. of Korea", "India", "China", "Rep. of Korea",
"USA", "Rep. of Korea", "Japan", "China", "Rep. of Korea", "India",
"China", "China", "India", "China", "China"), Partner = c("Saudi Arabia", "Canada", "Venezuela", "Mexico",
"Areas, nes", "Saudi Arabia", "United Arab Emirates", "Nigeria",
"Saudi Arabia", "Iraq", "Iran", "Qatar", "Kuwait", "United Arab Emirates",
"Angola", "Norway", "Colombia", "Oman", "United Kingdom", "Kuwait",
"Iran", "Gabon", "Indonesia", "Oman", "Kuwait", "Angola", "Iran",
"Oman", "Saudi Arabia", "Saudi Arabia", "Qatar", "Ecuador", "Indonesia",
"China", "Indonesia", "Australia", "Nigeria", "Yemen", "Fmr Sudan",
"Kuwait", "Iraq", "Viet Nam", "Iraq", "Australia", "Angola",
"United Arab Emirates", "Argentina", "Iran", "Trinidad and Tobago",
"Congo", "Yemen", "Iraq", "Viet Nam", "Australia", "Malaysia",
"Mexico", "Indonesia", "China", "Congo", "Ecuador", "Malaysia",
"Qatar", "Brunei Darussalam", "Norway"), Qty = c(69785202126, 68349221243, 68326932683,
64923669168, 57159000064, 53691639675, 52396394737, 46817696134,
38307387772, 31471382247, 25554794183, 19184268129, 18481591406,
16695296617, 16497467586, 16029110463, 15953011573, 15660839936,
14459452736, 13796910873, 11134838478, 10393629031, 10258716565,
9751327665, 9417368771, 8636634112, 7000465408, 6586187350, 5769723904,
5730211328, 5702528697, 5553458497, 5290777764, 5113191253, 4575188480,
4361612670, 3888963072, 3612423424, 3313590784, 3223781888, 3183182080,
3158472192, 3151280715, 3081015515, 3067260000, 2921931008, 2850134892,
2607684096, 2587749446, 2547349198, 2485083122, 2443798762, 2365431992,
2342513214, 2308853961, 2130664704, 1942125162, 1828376381, 1814260579,
1785874000, 1609282280, 1598901888, 1534923974, 1477843712, 1476737920,
1454356736, 1355873401, 1293729024, 1285355978, 1278701346, 1259876360,
1252518912, 1248772992, 1223383808, 1163368000, 1144188000, 1108399232,
1062041363, 1041526592, 977722731, 897418483, 877541040, 845556546,
801940467, 744316800, 739848000, 724177472, 694896000, 685405539,
672387008, 554965585, 540327751, 508204324, 4.87e+08, 457252032,
433428000, 430473920, 426744352, 408635880, 392727578, 390598528,
390189912, 389451923, 384376548, 350920922, 327039700, 285413702,
285143680, 275486240, 274015471, 264478000, 260122000, 238997756,
227806048, 204376795, 192144011, 150791409, 140634221, 135842986,
130777039, 129973032, 125115000, 124681401, 123443000, 120061792,
110795499, 106762492, 105548008, 84693986, 70275359, 57248174,
47944463, 40236018, 30783728, 18364000, 13419253, 12551365, 9631763,
5994199, 374000, 350000, 339115, 86420, 24000, 180)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -145L))

Removing redundant areas from a map in R (shapefile)

I plotted a few European countries on a map, but there are some outliers which I don't need. I tried to remove them from my spatial df using different ways suggested in similar questions but they didn't work for this case. Could you please give me your ideas on removing them? I appreciate it. The shape file is available here
EDIT: I need to remove these areas not only from the map, but also from the spatial data frame.
library(rgdal)
library(raster)
myCountries <- c("Austria", "Belgium", "Czech Republic", "Denmark", "Estonia", "Finland",
"France", "Germany", "Latvia", "Hungary", "Iceland", "Ireland", "Italy",
"Netherlands", "Norway", "Portugal", "Poland", "Spain", "Sweden", "Switzerland",
"Turkey", "United Kingdom")
countries <- readOGR('ne_110m_admin_0_countries.shp')
eurcountries <- countries[countries$NAME_EN %in% myCountries ,]
eurcountries2<-spTransform(eurcountries, CRS("+proj=longlat +datum=NAD83"))
plot(eurcountries2)
Here is how you can do that with terra (the replacement for raster):
myCountries <- c("Austria", "Belgium", "Czech Republic", "Denmark", "Estonia", "Finland",
"France", "Germany", "Latvia", "Hungary", "Iceland", "Ireland", "Italy",
"Netherlands", "Norway", "Portugal", "Poland", "Spain", "Sweden", "Switzerland",
"Turkey", "United Kingdom")
library(terra)
countries <- vect('ne_110m_admin_0_countries.shp')
eur <- countries[countries$NAME_EN %in% myCountries ,]
e <- ext(c(-28, 48, 35, 76)))
x <- crop(eur, e)
plot(x, "NAME_EN")
You can interactively find the extent you need for cropping by doing
plot(eur)
e <- draw()
# now click on the map twice
Or subset interactively, like this:
d <- disagg(eur)
plot(d)
s <- sel(d) # now draw a bounding box on the plot
a <- aggregate(s, "NAME_EN")
plot(a, "NAME_EN")
And you can coerce the SpatVector objects to sp or sf types like this:
sf <- sf::st_as_sf(x)
library(raster)
sp <- as(x, "Spatial")
Or vice versa with:
y <- vect(sf)
Instead of using the SP package, I find the SF package is better as it plays well with ggplot2. Then limiting the canvas is straightforward and adds the ability to colour the countries.
library(rgdal)
library(ggplot2)
myCountries <- c("Austria", "Belgium", "Czech Republic", "Denmark", "Estonia", "Finland",
"France", "Germany", "Latvia", "Hungary", "Iceland", "Ireland", "Italy",
"Netherlands", "Norway", "Portugal", "Poland", "Spain", "Sweden", "Switzerland",
"Turkey", "United Kingdom")
countries <- readOGR("C:/R/projects/ne_110m_admin_0_countries/ne_110m_admin_0_countries.shp")
eurcountries <- countries[countries$NAME_EN %in% myCountries, ]
eurcountries3 <- sf::st_as_sf(eurcountries)
ggplot(eurcountries3) +
geom_sf(aes(fill = ADMIN)) +
lims(x = c(50,-40), y = c(30, 74)) +
guides(fill = "none") +
theme_void()

ifelse statement - add a variable based on a condition

I am trying to add a factor variable "Economy" with levels "Developed" and "Developing" to my dataset that has a list of countries.
What am I doing wrong?
Developed <- data.frame(c("Andorra", "Faroe Islands", "Ireland", "Monaco", "Spain", "Australia", "Finland",
"Israel", "Netherlands", "Sweden", "Austria", "France", "Italy", "New Zealand", "Switzerland",
"Belgium", "Germany", "Japan", "Norway", "Turkey", "Bermuda", "Greece", "Liechtenstein",
"Portugal", "United Kingdom", "Canada", "Holy See", "Luxembourg", "San Marino", "United States",
"Denmark", "Iceland", "Malta", "South Africa", "Hong Kong", "South Korea", "Singapore", "Taiwan"))
names(Developed) <- "Country"
total$Economy <- ifelse(d$Country==Developed$Country, "Developed", "Developing")
It produces the following error:
Warning messages:
1: In is.na(e1) | is.na(e2) :
longer object length is not a multiple of shorter object length
2: In `==.default`(data$Country, Developed$Country) :
longer object length is not a multiple of shorter object length
#DJJ,
ifelse(d$Country%in%Developed$Country, "Developed", "Developing")
worked perfectly! Problem solved.

How to generate maps with different section highlighted each time with a for loop?

I would like to generate a set of maps in R with all of them having the same background (a focus on Europe) BUT each of them having one EU country highlighted in another color. And I can't seem to figure out how to write the for loop to get that...
Here is my code:
require(rgdal)
setwd(...) #where I have my GIS shapefile
world <- readOGR(dsn = ".", layer = "TM_WORLD_BORDERS-0.2")
#Subset European countries
#List of "european" countries + shapefile
europe <- c("Russia", "Isle of Man", "Channel Islands", "Faroe Islands",
"France", "Denmark", "Iceland", "Germany", "Romania", "Poland", "Portugal",
"United Kingdom", "Spain", "Sweden", "Lithuania", "Ireland", "Italy",
"Netherlands", "Norway", "Ukraine", "Latvia", "Estonia", "Finland",
"Bulgaria", "Belgium", "Montenegro", "Serbia and Montenegro", "Slovenia",
"Albania", "Greece", "Croatia", "Malta")
europe <- subset(world, NAME %in% europe)
#List of countries in the EU + shapefile
EU <- c("Isle of Man", "Channel Islands", "Faroe Islands", "France",
"Denmark", "Germany", "Romania", "Poland", "Portugal", "Spain", "Sweden",
"Lithuania", "Ireland", "Italy", "Netherlands", "Ukraine", "Latvia", "Estonia",
"Finland", "Bulgaria", "Belgium", "Montenegro", "Serbia and Montenegro",
"Slovenia", "Albania", "Greece", "Croatia", "Malta")
EU <- subset(europe, NAME %in% EU)
#Generate one map per highlighted country
eucountries <- unique(europe$NAME)
for(i:length(eucountries))
{
print(i)
png(paste(i,".png",sep=""), 200, 200)
map("world", ylim=c(35,70), xlim=c(-20,45), col="#BFBFBF", fill=TRUE)
plot(eucountries, add=TRUE, col="#769EB2", namesonly=TRUE)
dev.off()
}
I want to produce one png per country. Each png will have one specific country highlighted with a different color. The full map will be plotted each time.
Thanks to vpipkt's comment that indicated that map()$names does provide a list of names of the things (polygons I suspect) that are plotted I could come up with a much more elgant solution:
building an index of for those polygons that are named like countries
using that information to build a color vector to color the countries
Note: the borders provided by the maps packae seem a litle outdated, e.g. Yugoslavia
# library
library(maps)
# options
old <- par()$mar
par("mar"=c(0,0,0,0))
YLIM <- c(35,70)
XLIM <- c(-20,45)
# plotting
for(country in c("Germany", "Ireland", "Spain", "Greece", "Denmark", "Yugoslavia") )
{
polygon_names <- map("world", ylim=YLIM, xlim=XLIM)$names
index <- grep(country, polygon_names)
colvec <- rep("white", length(polygon_names))
colvec[index] <- "red"
png(paste0(country,".png"))
map("world", ylim=YLIM, xlim=XLIM, col=colvec, fill=TRUE)
dev.off()
}
# resetting options
par("mar"=old)
Inside your loop, try
plot(eucountries[i], add=TRUE, col="#769EB2", namesonly=TRUE)
in place of your current plot call. Note the subset of eucountries.

ggplot: how to limit output in bar plot so only most frequent occurrences are shown?

I have been searching for this simple thing for hours now, but to no avail. I have a dataframe with one of the columns the variable "country". I want two things the following:
Plot the most frequent countries, most frequent on top (partial solution found EDIT full solution found >> focus question on limiting output in bar plot based on frequency);
Only show the top x "most frequent" countries, moving the rest into 'Other' variable.
I tried to ggplot table() or summary() but that does not work. Is it even possible within ggplot, or should I use barchart (I managed to do this using barchart, just using summary(df$something) and adding max = x). I also wanted to stack the output (different questions about country).
Most frequent countries on top:
ggplot(aDDs,aes(x=
factor(answer,
levels=names(sort(table(answer),increasing=TRUE))
),fill=question
)
) + geom_bar() + coord_flip()
Suggestions are very very welcome.
====== EDIT3:
I continued working on the code based on the suggestion by #CMichael, but now encountered another, quite strange, thing. Because this 'ifelse' problem concerns a slightly one question than my original one, I have posted a separate question for this matter. Please check it here: R: ifelse function returns vector position instead of value (string)
====== EDIT:
The aDDs example is reproduced below - aDDs dataset can be downloaded here:
temp <- structure(list(student = c(2270285L, 2321254L, 75338L, 2071594L,1682771L, 1770356L, 2155693L, 3154864L, 3136979L, 2082311L),answer = structure(c(181L, 87L, 183L, 89L, 115L, 183L, 172L,180L, 175L, 125L), .Label = c("Congo", "Guinea-Bissau", "Solomon Islands","Central African Rep", "Comoros", "Equatorial Guinea", "Liechtenstein","Nauru", "Brunei", "Djibouti", "Kiribati", "Papua New Guinea","Samoa", "South Sudan", "Tajikistan", "Tonga", "Bhutan","Gabon", "Laos", "Lesotho", "Maldives", "Micronesia", "St Kitts and Nevis","Mozambique", "Niger", "Andorra", "Cape Verde", "Mauritania","Antigua and Deps", "Chad", "Guinea", "Malta", "Burundi","Eritrea", "Iceland", "Kyrgyzstan", "Turkmenistan", "Azerbaijan","Dominica", "Belize", "Malawi", "Mali", "Moldova", "Benin","Cuba", "Gambia", "Luxembourg", "St Lucia", "Angola", "Cambodia","Georgia", "Madagascar", "Oman", "Kosovo", "Kuwait", "Namibia","Bahrain", "Congo - Democratic Rep", "Montenegro", "Senegal","Sierra Leone", "Togo", "Botswana", "Fiji", "Libya", "Uzbekistan","Guyana", "Mongolia", "Somalia", "Zambia", "Estonia", "Ivory Coast","Myanmar", "Grenada", "Qatar", "Saint Vincent and the Grenadines","Tanzania", "Armenia", "Bahamas", "Belarus", "Burkina", "Liberia","Afghanistan", "Latvia", "Yemen", "Mauritius", "Albania","Barbados", "Iraq", "Macedonia", "Nicaragua", "Panama", "Slovenia","Lebanon", "Slovakia", "Kazakhstan", "Paraguay", "Korea South","Suriname", "Czech Republic", "Rwanda", "Haiti", "Lithuania","Israel", "Zimbabwe", "Cyprus", "Honduras", "Uruguay", "Syria","Finland", "Tunisia", "Taiwan", "Uganda", "Denmark", "Austria","Sri Lanka", "Vietnam", "Bosnia Herzegovina", "Thailand","Norway", "Trinidad and Tobago", "Switzerland", "Nepal","Sudan", "Jamaica", "Japan", "United Arab Emirates", "Bolivia","New Zealand", "Ethiopia", "Jordan", "Cameroon", "Croatia","Sweden", "Kenya", "Singapore", "Guatemala", "Ireland Republic","Saudi Arabia", "Bulgaria", "Malaysia", "Belgium", "Dominican Republic","Algeria", "El Salvador", "Bangladesh", "Serbia", "Ghana","Costa Rica", "Indonesia", "Hungary", "Venezuela", "Ecuador","Ukraine", "Romania", "Turkey", "China", "Morocco", "Russian Federation","Peru", "South Africa", "Argentina", "Portugal", "Iran","Poland", "Italy", "Chile", "France", "Germany", "Australia","Philippines", "Egypt", "Greece", "Nigeria", "Canada", "Pakistan","United Kingdom", "Mexico", "Colombia", "Brazil", "Netherlands","Spain", "India", "United States"), class = "factor"), question = c("C1-pres","C1-pres", "C1-pres", "C1-pres", "C1-pres", "C1-pres", "C1-pres","B1-pres", "B1-pres", "B1-pres")), .Names = c("student","answer", "question"), row.names = c("156", "203", "280", "347","412", "478", "534", "1649651", "1649691", "1649763"), class = "data.frame")
For the filtering question you should introduce a new column:
data$filteredCountry = ifelse(data$value > threshold, data$country, "other")
Now you can use filteredCountry as your x in the aesthetics.
The data ordering question pops up every now and then (e.g., ggplot2: sorting a plot). You need to order your country factor levels by the underlying values. Your reorder command seems to sort by country name again, I would expect something like reorder(country,frequency) but sample data would help.
UPDATE:
With the now provided data it becomes obvious that you need to create summary dataset:
data <- read.table("aDDs.csv",sep=",",header=T)
require(plyr)
summary <- ddply(data,.(answer),summarise,freq=length(answer))
This yields the data frame summary with one entry for each country (181 in total). Now you can do the filtering and the reordering:
threshold = quantile(summary$freq,0.9)
summary $filteredCountry = ifelse(summary$freq > threshold, summary$answer, "other")
summary$filteredCountry = reorder(summary$filteredCountry,-summary$freq)
Now you can plot:
require(ggplot2)
p=ggplot(data=summary,aes(x=filteredCountry,y=freq))
p = p+geom_bar(aes(fill=filteredCountry),stat="identity")
p
Thanks to suggestions from #CMichael and answers to another - related - post here on SO. I managed to create a stacked and ordered bar plot using ggplot:
create a list with most frequent country names
temp <- row.names(as.data.frame(summary(aDDs$answer, max=12))) # create a df or something else with the summary output.
aDDs$answer <- as.character(aDDs$answer) # IMPORTANT! Here was the problem: turn into character values
create new column that filters top results
aDDs$top <- ifelse(
aDDs$answer %in% temp, ## condition: match aDDs$answer with row.names in summary df
aDDs$answer, ## then it should be named as aDDs$answer
"Other" ## else it should be named "Other"
)
aDDs$top <- as.factor(aDDs$top) # factorize the output again
plot
ggplot(aDDs,aes(x=
factor(top,
levels=names(sort(table(top),increasing=TRUE))
),fill=question
)
) + geom_bar() + coord_flip()
And here the output (still needs some tweaking, but it is what I wanted):

Resources