2

I have a data with longitude, latitude and value at each grid. A grid may have more than one value so I set alpha to visualize multiple values. My aim is to fill grids with three different ranges. If the value is zero then that grid would be empty.

library(maps)
library(ggplot2)
data <- read.csv("G:/mydata.csv")
g1 <- ggplot(aes(x=x, y=y, fill= A), data=data) +
  geom_tile(data=subset(data, A > 1970 &  A < 1980),fill = "black", alpha = 0.5)+
  geom_tile(data=subset(data, B > 1970 & B < 1980),fill = "black", alpha = 0.5)+
  geom_tile(data=subset(data, C > 1970 & C < 1980),fill = "black", alpha = 0.5)+
  geom_tile(data=subset(data, A > 1979 & A < 1990),fill = "blue", alpha = 0.5)+
  geom_tile(data=subset(data, B> 1979 & B < 1990), fill = "blue", alpha = 0.5)+
  geom_tile(data=subset(data, C > 1979 & C < 1990),fill = "blue", alpha = 0.5)+
  geom_tile(data=subset(data, A > 1989),fill = "red", alpha = 0.5)+
  geom_tile(data=subset(data, B > 1989),fill = "red", alpha = 0.5)+
  geom_tile(data=subset(data, C > 1989),fill = "red", alpha = 0.5)+
  theme_classic()

The Image

is wrong. As blue grids are bigger. I could not find out the mistake. I followed the link but could not make it. I guess there is something trivial which I am missing. My data can be accessed here. Many thanks in advance.

Community
  • 1
  • 1
Pankaj
  • 1,296
  • 2
  • 13
  • 23
  • `geom_tile` doesn't really work the way you imagine it to. It calculates a new grid for each call to `geom_tile`. Need to think about this. – Mike Wise Dec 21 '15 at 15:11

1 Answers1

2

Sorry, can't do it the way you envisioned it. Not enough flexiblity that I could see. But one can do this:

library(maps)
library(ggplot2)

ddf <- read.csv("mydata.csv")

setz <- function(dddf,zvek,lev=0,fillclr){
  dddf$z <- as.numeric(zvek)
  dddf$lev <- lev
  dddf$color <- "white"
  dddf$fill <- ifelse(zvek,fillclr,"gray")
  return(dddf)
}
df1<-setz(ddf,ddf$A>1970 & ddf$A<1980,"A>1970 & A<1980","black")
df2<-setz(ddf,ddf$B>1970 & ddf$B<1980,"B>1970 & B<1980","black")
df3<-setz(ddf,ddf$C>1970 & ddf$C<1980,"C>1970 & C<1980","black")

df4<-setz(ddf,ddf$A>1979 & ddf$A<1990,"A>1979 & A<1990","blue")
df5<-setz(ddf,ddf$B>1979 & ddf$B<1990,"B>1979 & B<1990","blue")
df6<-setz(ddf,ddf$C>1979 & ddf$C<1990,"C>1979 & C<1990","blue")

df7<-setz(ddf,ddf$A>1989,"A>1989","red")
df8<-setz(ddf,ddf$B>1989,"B>1989","red")
df9<-setz(ddf,ddf$C>1989,"C>1989","red")

ddg <- rbind( df1,df2,df3, df4,df5,df6, df7,df8,df9 )

g1 <- ggplot(data=ddg,aes(x=x, y=y,fill=fill,color=color)) +
  geom_tile() +
  scale_color_identity() +
  scale_fill_identity() +
  facet_wrap(~lev)
  theme_classic()
print(g1)

Which yields this:

enter image description here

Mike Wise
  • 22,131
  • 8
  • 81
  • 104