I am trying to visualize some data from countries in a world map using R and ggplot2
. I am using the following code(sample):
WorldData <- map_data('world')
df <-data.frame(region=c('Hungary','Lithuania','Argentina'),value=c(4,10,11))
Total <- merge(WorldData,df,by='region')
and for plotting using ggplot:
p <- ggplot()
p <- p + geom_polygon(data=Total, aes(x=long, y=lat, group = group,fill=Total$value),colour="white") +
scale_fill_continuous(low = "thistle2", high = "darkred", guide="colorbar")
P1 <- p + theme_bw() + labs(fill = "legend" ,title = "Title", x="", y="")
P1 + scale_y_continuous(breaks=c()) + scale_x_continuous(breaks=c()) + theme(panel.border = element_blank())
The output is this:
I believe that the problem is in the merge
because when I change the data option in geom_polygon
to WorldData
and the fill
option to 1
I have the following result:
Is this happening because I do not have data from all the countries in df
? How can I overtake that?
edit: What I would like is to plot the whole map. (I was not clear in my description)
You can also work in "layers" as other GIS environments let you (which will also let you not merge the data). This can be achieved in many ways, but I like to use geom_map
:
library(ggplot2)
library(dplyr)
WorldData <- map_data('world') %>% filter(region != "Antarctica") %>% fortify
df <- data.frame(region=c('Hungary','Lithuania','Argentina'),
value=c(4,10,11),
stringsAsFactors=FALSE)
p <- ggplot() +
geom_map(data = WorldData, map = WorldData,
aes(x = long, y = lat, group = group, map_id=region),
fill = "white", colour = "#7f7f7f", size=0.5) +
geom_map(data = df, map=WorldData,
aes(fill=value, map_id=region),
colour="#7f7f7f", size=0.5) +
coord_map("rectangular", lat0=0, xlim=c(-180,180), ylim=c(-60, 90)) +
scale_fill_continuous(low="thistle2", high="darkred", guide="colorbar") +
scale_y_continuous(breaks=c()) +
scale_x_continuous(breaks=c()) +
labs(fill="legend", title="Title", x="", y="") +
theme_bw()
p
That also has a projection (via coord_map
) so you'll get consistent output and gets rid of Antarctica.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With