Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geom_map borders in ggplot2 - revisited

Tags:

r

map

ggplot2

I have a similar problem as @Mike in this question. The question is how to set the outline colors of the regions in a map plot.

The proposed solution there is to add a geom_polygon to plot over the borders. This works, as long as the whole area is plotted. When trying try to restrict to a sub-area, the polygons get drawn oddly (presumably because some vertices get dropped). Using the standard geom_map example:

# Create example data
ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))
values <- data.frame(id = ids, value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5))
positions <- data.frame(
  id = rep(ids, each = 4),
  x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3, 0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
  y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5, 2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)

# Plot data
ggplot(values, aes(fill = value)) + 
    geom_map(aes(map_id = id), map = positions) +
    geom_polygon(aes(x,y,group=id), fill = NA, colour = 'red', data = positions) +
    expand_limits(positions) +
    ylim(0, 3)

A possible workaround is using the colour aesthetic in geom_map and then manually choose the outline color with scale_colour_manual, as follows:

ggplot(values, aes(fill = value)) + 
    geom_map(aes(map_id = id, colour = 'white'), map = positions) +
    scale_colour_manual(values=c('white')) +
    expand_limits(positions) +
    ylim(0, 3)

So I have two questions:

  1. Why does geom_polygon not work properly when the axis limits are restrained?
  2. Is there a more elegant solution to color the outlines than the one showed here?

Below are the plot outputs. Many thanks in advance.

Did not work properly using geom_polygonWorks but is not very elegant

like image 247
yellowcap Avatar asked May 13 '12 15:05

yellowcap


1 Answers

I believe you are correct as to why it doesn't work. Restricting the x or y limits using xlim or ylim clips the data prior to plotting. This will end up omitting some vertices from your polygon, so some stuff won't get plotted.

This is why there's coord_cartesian, which allows you to adjust the x and y limits without clipping the data. It will "zoom" into the correct region, rather than clipping and then plotting.

So instead of ylim, try + coord_cartesian(ylim = c(0,3)).

like image 109
joran Avatar answered Nov 13 '22 01:11

joran