0

Following the very good example provided here, I tried to make the following filled contour plot.

x<-seq(1,11,.03)                    # note finer grid
y<-seq(1,11,.03)
xyz.func<-function(x,y) {(x^2+y^2)}
gg <- expand.grid(x=x,y=y)
gg$z <- with(gg,xyz.func(x,y))      # need long format for ggplot
brks <- cut(gg$z,breaks=c(1, 2, 5, 10, 30, 50, 100, 200))
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(7,"YlOrRd"))+
  scale_x_continuous(expand=c(0,0))+
  scale_y_continuous(expand=c(0,0))+
  coord_fixed()

The result looks like this:

Not what I expected

The thing is, the contours are sorted by alphabetical order, not by ascending values.

How would you change the order of the colors to be by ascending z values?

At first, I thought about adding "0"s in front of the values. I tried something like:

brks <- gsub(pattern = "(\b[0-9]\b)", replacement = "0$1", x = brks)

But it does not work.

Moreover, it would only add one zero in front of single digits, and 100 would still be before 02.

Actually, I'm not completely satisfied with this workaround, as 001 - 002 does not look beautiful.

Community
  • 1
  • 1
Ben
  • 6,321
  • 9
  • 40
  • 76

1 Answers1

1

Make your breaks an ordered factor:

x<-seq(1,11,.03)                    # note finer grid
y<-seq(1,11,.03)
xyz.func<-function(x,y) {(x^2+y^2)}
gg <- expand.grid(x=x,y=y)
gg$z <- with(gg,xyz.func(x,y))      # need long format for ggplot

brks <- cut(gg$z,breaks=c(1, 2, 5, 10, 30, 50, 100, 200), ordered_result = T)
levels(brks) <- gsub(","," - ", levels(brks), fixed=TRUE)
levels(brks) <- gsub("\\(|\\]","", levels(brks))

gg$brks <- brks  # reformat guide labels
ggplot(gg,aes(x,y)) + 
   geom_tile(aes(fill=brks))+
   scale_fill_manual("Z",values=brewer.pal(7,"YlOrRd"))+
   scale_x_continuous(expand=c(0,0))+
   scale_y_continuous(expand=c(0,0))+
   coord_fixed()
toni057
  • 582
  • 1
  • 4
  • 10