1
votes

I am trying to combine a balloon plot with a basic map created from a basic China shapefile sourced in www.gadm.org. My goal is to create a balloon plot with data from a separate dataframe as a layer on top of the shapefile map, using longitude and latitude to pinpoint the location of the balloons.

library(ggplot2)
library(maps)
library(maptools)

China_basic <- readShapePoly("CHN_adm0.shp")
china_basemap <-fortify(China_shp)

chinachart <- ggplot(china_basemap,aes(x=long,y=lat,group=group)) + 
  geom_polygon(colour="white") 

So far so good, however, now I want to add additional data from a separate dataframe to the plot:

cit <- c('Beijing','Shanghai','Guangzhou')
lng <-  c(116.23,121.3,113.16)
lt <- c(39.55,31.12,23.08)
pop <- c(18590000,24256800,11264800)
dat <- c(400,560,700)

newdata <- data.frame(cit,lng,lt,pop,dat)

chinachart + geom_point(x=newdata$lng,y=newdata$lt,size=newdata$pop,fill=newdata$dat,
shape=21,colour='black')+
  scale_colour_gradient2(low="white",mid="yellow",high="red",midpoint=560)

This gives me the following error, and I'm not sure what I have done wrong with my syntax:

Error: Incompatible lengths for set aesthetics: shape, colour, size, fill, x, y

Any help much appreciated.

1

1 Answers

1
votes

One issue is using scale_colour_gradient2 vs scale_fill_gradient2 (you mapped the fill aesthetic, not color).

Another is how you built the geom_point layer.

Here's the correct version with a slightly different mapping idiom:

library(sp)
library(raster)
library(rgeos)
library(ggplot2)
library(ggthemes)

china_basic <- getData("GADM", country="CHN", level=0)
china_basic <- SpatialPolygonsDataFrame(gSimplify(china_basic, 0.05), china_basic@data)
china_basemap <- fortify(china_basic)

gg <- ggplot()
gg <- gg + geom_map(data=china_basemap, map=china_basemap,
                    aes(x=long, y=lat, map_id=id),
                    color="white")
gg <- gg + coord_map("azequalarea")
gg <- gg + theme_map()
china_chart <- gg

cit <- c('Beijing',  'Shanghai', 'Guangzhou')
lng <- c(116.23, 121.3, 113.16)
lat <- c(39.55, 31.12, 23.08)
pop <- c(18590000, 24256800, 11264800)
dat <- c(400, 560, 700)

new_data <- data.frame(cit, lng, lat, pop, dat, stringsAsFactors=FALSE)

china_chart <- china_chart +
  geom_point(data=new_data, 
             aes(x=lng, y=lat, size=pop, fill=dat),
             shape=21, colour='black')
china_chart <- china_chart + 
  scale_fill_gradient2(low="white", mid="yellow", high="red", midpoint=560)
china_chart <- china_chart + theme(legend.position="bottom")
china_chart

enter image description here