2

There is a way to simply create breaks in the stat_contour() function of ggplot2 using

stat_contour(breaks = ...)

Unfortunately, I find, the same can not be applied for the geom_tile() function. There is a way to partly solve this problem using the cut() function to create sections that can be filled then, e.g.

data$br <- cut(data$z, breaks=seq(...))
ggplot(data, aes(x,y,z)) + geom_tile(aes(fill=br))

This creates a legend in the plot which shows intervals though, not single values. Is there a simpler way to fill the tiles by using something similar to breaks?

A way to achieve the filled sections using the cut() function can be found by user @jlhoward, which creates the following result:

Example image

x<-seq(1,11,.03)                    # note finer grid
y<-seq(1,11,.03)
xyz.func<-function(x,y) {-10.4+6.53*x+6.53*y-0.167*x^2-0.167*y^2+0.0500*x*y}
gg <- expand.grid(x=x,y=y)
gg$z <- with(gg,xyz.func(x,y))      # need long format for ggplot
library(ggplot2)
library(RColorBrewer)               #for brewer.pal()
brks <- cut(gg$z,breaks=seq(0,100,len=6))
brks <- gsub(","," - ",brks,fixed=TRUE)
gg$brks <- gsub("\\(|\\]","",brks)  # reformat guide labels
ggplot(gg,aes(x,y)) + 
  geom_tile(aes(fill=brks))+
  scale_fill_manual("Z",values=brewer.pal(6,"YlOrRd"))+
  scale_x_continuous(expand=c(0,0))+
  scale_y_continuous(expand=c(0,0))+
  coord_fixed()

That example does not fully please my needs though, I'd prefer no intervals in the legend (also, the values are descending not ascending, which I can't seem to figure out why).

Any help would be greatly appreciated!

Community
  • 1
  • 1
oepix
  • 151
  • 2
  • 12

1 Answers1

1

If I'm understanding correctly, you just want the scale labels fixed, and the scale reversed. After the previous good work of @jlhoward, this is nice and easy.

We want to change the labels, so I'm using strsplit to remove the range id. We want to flip the legend, so I'm using guide = guide_legend(reverse=TRUE):

x<-seq(1,11,.03)                    # note finer grid
y<-seq(1,11,.03)
xyz.func<-function(x,y) {-10.4+6.53*x+6.53*y-0.167*x^2-0.167*y^2+0.0500*x*y}
gg <- expand.grid(x=x,y=y)
gg$z <- with(gg,xyz.func(x,y))      # need long format for ggplot
library(ggplot2)
library(RColorBrewer)               #for brewer.pal()
brks <- cut(gg$z,breaks=seq(0,100,len=6))
brks <- gsub(","," - ",brks,fixed=TRUE)
gg$brks <- sapply(brks, function(x){strsplit(x, "[( ]")[[1]][[2]]})
ggplot(gg,aes(x,y)) + 
  geom_tile(aes(fill=brks))+
  scale_fill_manual("Z",values=brewer.pal(6,"YlOrRd"), guide = guide_legend(reverse=TRUE))+
  scale_x_continuous(expand=c(0,0))+
  scale_y_continuous(expand=c(0,0))+
  coord_fixed()

enter image description here

jeremycg
  • 24,657
  • 5
  • 63
  • 74
  • This works for my purpose, thank you! As for the 'breaks' part: I assume using the cut() function is the only way to fill the intervals? – oepix Sep 21 '15 at 14:01