4

I'm trying to plot a continuous variable on space. I saw this example that gets the same result that I need:

library("MASS")
library("ggplot2")
library(reshape2) 

DB<-melt(volcano)
ggplot(DB, aes(x=Var1, y=Var2, fill=value)) +geom_tile()

enter image description here

So I did with my data:

library(repmis)
url<-"https://www.dropbox.com/s/4m5qk32wjgrjq40/dato.RDATA"
source_data(url)

library(ggplot2)
ggplot(dato,aes(y=variable,x=y,fill=value))+geom_tile()

enter image description here

That's wonderful. But my "x" and "y" are kilometers distance (east and north) from a point in space. I transformed these in latitude and longitude. But now my plot doesn't work!

ggplot(dato,aes(y=lat,x=long,fill=value))+geom_tile()

enter image description here

I don't understand why. Anyway plotting my data like points the result is very similar:

ggplot(dato,aes(y=lat,x=long,fill=value))+geom_point()
ggplot(dato,aes(y=variable,x=y,fill=value))+geom_point()
dax90
  • 1,088
  • 14
  • 29
  • Possibly related: http://docs.ggplot2.org/0.9.3.1/scale_gradient.html , http://docs.ggplot2.org/0.9.2.1/scale_gradient2.html – CinchBlue Jul 19 '15 at 21:04
  • 1
    I think it's because the latitude and longitude points are not spaced evenly and hence don't form a grid. If distance is spaced evenly then the coordinates can't be and vice versa. If you plot the latitude and longitude points you'll find that they are very slightly tilted. You'll probably have to do some interpolation to get it to work. – maccruiskeen Jul 19 '15 at 21:15
  • I find the interpolation a little complicated. Is there an alternative to geom_tile to have the same result? – dax90 Jul 19 '15 at 21:23
  • Sorry just saw this comment now but looks like you got a good solution :) – maccruiskeen Jul 19 '15 at 23:38

1 Answers1

14

You can cheat a bit and use geom_point with a square shape:

#devtools::install_github("sjmgarnier/viridis")
library(viridis)
library(ggplot2)
library(ggthemes)
library(scales)
library(grid)

gg <- ggplot(dato)
gg <- gg + geom_point(aes(x=long, y=lat, color=value), shape=15, size=5)
gg <- gg + coord_equal()
gg <- gg + scale_color_viridis(na.value="#FFFFFF00")
gg <- gg + theme_map()
gg <- gg + theme(legend.position="right")
gg

enter image description here

I did not project the lat/long pairs and just used coord_equal. You should use a proper projection for the region being mapped.

And, now you have me curious as to what those hot spots are around Milan :-)

gmap <- get_map(location=c(9.051062, 45.38804, 9.277473, 45.53438),
                 source="stamen", maptype="toner", crop=TRUE)
gg <- ggmap(gmap)
gg <- gg + geom_point(data=dato, aes(x=long, y=lat, color=value), shape=15, size=5, alpha=0.25)
gg <- gg + coord_map()
gg <- gg + scale_color_viridis(na.value="#FFFFFF00")
gg <- gg + theme_map()
gg <- gg + theme(legend.position="right")
gg

enter image description here

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205