I make the following rworldplot
:
library(rworldmap)
#> Loading required package: sp
#> ### Welcome to rworldmap ###
#> For a short introduction type : vignette('rworldmap')
library(RColorBrewer)
test.data <- data.frame(
country = c('USA','Denmark','Australia','Germany'),
value = c(4000,1000,2300,100)
)
sPDF <- joinCountryData2Map(test.data,joinCode = "NAME",nameJoinColumn = "country")
#> 4 codes from your data successfully matched countries in the map
#> 0 codes from your data failed to match with a country code in the map
#> 239 codes from the map weren't represented in your data
colourPalette <- brewer.pal(4,'Reds')
mapParams <- mapCountryData(sPDF, nameColumnToPlot="value", colourPalette=colourPalette, catMethod=c(0,500,1000,2300,5000), addLegend=FALSE, mapTitle = 'TEST')
do.call( addMapLegend, c( mapParams
, legendLabels="all"
, legendWidth=0.5 ))
For clarity I want to add a barplot as well:
library(ggplot2)
barplot <- ggplot(test.data, aes(x=reorder(country,-value), y = value)) +
geom_bar(stat='identity', fill = 'darkred') +
theme_classic()
barplot
Ideally I want to combine the rworldmap plot and the ggplot in one figure using e.g. grid.arrange
or the cowplot
package. I know this is easy for different ggplot
objects however the do.call
plots the rworldmap directly, hence I don't know how I can get it to word like grid.arrange(<rworlddmapplot>, barplot)
.
The plot_grid()
function from cowplot can take a function argument that draws the plot you want to show.
library(rworldmap)
#> Loading required package: sp
#> ### Welcome to rworldmap ###
#> For a short introduction type : vignette('rworldmap')
library(RColorBrewer)
test.data <- data.frame(
country = c('USA','Denmark','Australia','Germany'),
value = c(4000,1000,2300,100)
)
draw_map <- function(test.data) {
function() {
sPDF <- joinCountryData2Map(test.data,joinCode = "NAME",nameJoinColumn = "country")
colourPalette <- brewer.pal(4,'Reds')
mapParams <- mapCountryData(sPDF, nameColumnToPlot="value", colourPalette=colourPalette, catMethod=c(0,500,1000,2300,5000), addLegend=FALSE, mapTitle = 'TEST')
do.call( addMapLegend, c( mapParams
, legendLabels="all"
, legendWidth=0.5 ))
}
}
library(ggplot2)
barplot <- ggplot(test.data, aes(x=reorder(country,-value), y = value)) +
geom_bar(stat='identity', fill = 'darkred') +
theme_classic()
library(cowplot)
#>
#> ********************************************************
#> Note: As of version 1.0.0, cowplot does not change the
#> default ggplot2 theme anymore. To recover the previous
#> behavior, execute:
#> theme_set(theme_cowplot())
#> ********************************************************
plot_grid(barplot, draw_map(test.data))
#> 4 codes from your data successfully matched countries in the map
#> 0 codes from your data failed to match with a country code in the map
#> 239 codes from the map weren't represented in your data
Created on 2019-08-26 by the reprex package (v0.3.0)