Barplots on a Map

Viewed 7541

I am trying to plot vertical bar plots over a map. I went through examples online but somehow not being able to.

My data is currently in this format:

University| Count | Category | lat | long

Here is the code that I am trying execute:

library(ggplot2)
library(ggmap)
library(ggsubplot)

df1 <- data.frame(
  University = c(rep("University1", 4), rep("University2", 4), rep("University3", 4), 
    rep("University4", 4)),
  Count = sample(1:10, 16, replace = T),
  Category = rep(c("A", "B", "C", "D")),
  lat = c(rep(10.902469, 4), rep(17.921959, 4), rep(18.606910, 4), rep(13.202366, 4)),
  long = c(rep(76.90020, 4), rep(83.42510, 4), rep(73.87501, 4), rep(77.62340, 4))
)

india <- get_map("India", zoom = 5)
p <- ggmap(india)
p + geom_subplot(data = df1, mapping=aes(x = long, y = lat, group = University,
subplot= geom_bar(aes(x = Category, y = Count, color = Category, stat = "identity"))))

When I run the above code, I get the following error:

Error in get(x, envir = this, inherits = inh)(this, ...) : 
   could not find function "%:::%"
2 Answers

In fact we can use geom_errorbar() to add a bar in map actually. As long as we set the x and y of geom_errorbar() is longitude and latitude; and the ymin and ymax is stat of your data .

library(tidyverse)

plant_data <- read.csv("DV.csv")
colnames(plant_data) <- c("name", "lat", "lon", "p", "t", "hmi")
head(plant_data)
# name      lat      lon    p    t         hmi
# 1 Dodonaea viscosa subsp. viscosa -17.3000 145.9667 4084 24.1 8.905719509
# 2 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
# 3 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
# 4 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
# 5 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
# 6 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823

plot part

aus <- map_data('world', region = "(Australia)|(Indonesia)|(Papua New Guinea)")
ggplot() +
  geom_polygon(data = aus, aes(x = long, y = lat, group = group), 
               fill = "gray80") + 
  geom_point(data = plant_data, aes(x = lon, y = lat), color = '#00CC00') +
  coord_map(xlim = c(110, 160), ylim = c(-45, -5)) +
  ggtitle("植物分布") + 
  theme(plot.title = element_text(hjust = 0.5)) + 
  geom_errorbar(data = plant_data[c(50, 99), ], 
                aes(x = lon,ymin=lat-3,ymax=lat+1), 
                color='blue', size = 3, width=0)

this part is very smart:

geom_errorbar(data = plant_data[c(50, 99), ], 
                aes(x = lon,ymin=lat-3,ymax=lat+1), 
                color='blue', size = 3, width=0)

it is very amazing!!

enter image description here

Related