Osmo Salomaa
unread,May 19, 2011, 3:39:38 AM5/19/11Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Sign in to report message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to ggplot2
For anyone interested, here are two functions I wrote a while back to
simplify adding a very simple scalebar to a plot.
hscale_segment = function(breaks, ...)
{
y = unique(breaks$y)
stopifnot(length(y) == 1)
dx = max(breaks$x) - min(breaks$x)
dy = 1/30 * dx
hscale = data.frame(ix=min(breaks$x), iy=y, jx=max(breaks$x),
jy=y)
vticks = data.frame(ix=breaks$x, iy=(y - dy), jx=breaks$x, jy=(y +
dy))
df = rbind(hscale, vticks)
return(geom_segment(data=df,
aes(x=ix, xend=jx, y=iy, yend=jy),
...))
}
hscale_text = function(breaks, ...)
{
dx = max(breaks$x) - min(breaks$x)
dy = 2/30 * dx
breaks$y = breaks$y + dy
return(geom_text(data=breaks,
aes(x=x, y=y, label=label),
hjust=0.5,
vjust=0,
...))
}
Then it's a simple matter of defining the break points for the
scalebar and adding layers with the two above functions to your plot.
Defining the breaks obviously depends on your coordinate system, the
below example is for a projected metric coordinate system. (ymin,
xmax) is the lower right hand corner in which the scalebar is being
placed.
scalebreaks = data.frame(x=seq(xmax - 11000, xmax - 1000, 5000),
y=(ymin + 1000),
label=c("0", "5", "10 km"))
plot = (ggplot(...)
+ ...
+ hscale_segment(scalebreaks, size=0.1)
+ hscale_text(scalebreaks, size=2)
+ ...
)
It will look about like this:
0 5 10 km
|--------|--------|
Adding a north arrow should be trivial, assuming you yourself know
which way north is.