Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually Set Scale of contour plot using geom_contour_filled

I would like manually adjust the scales of two contour plots such that each have the same scale even though they contain different ranges of values in the z-direction.
For instance, lets say that I want to make contour plots of z1 and z2:

x = 1:15
y = 1:15
z1 = x %*% t(y)
z2 = 50+1.5*(x %*% t(y))

data <- data.frame(
  x = as.vector(col(z1)),
  y = as.vector(row(z1)),
  z1 = as.vector(z1),
  z2 = as.vector(z2)
)

ggplot(data, aes(x, y, z = z1)) + 
  geom_contour_filled(bins = 8) 

ggplot(data, aes(x, y, z = z2)) + 
  geom_contour_filled(bins = 8) 

enter image description here enter image description here

Is there a way I can manually adjust the scale of each plot such that each contain the same number of levels (in this case bins = 8), the minimum is the same for both (in this case min(z1)), and the max is the same for both (max(z2))?

like image 344
Colin M. Lynch Avatar asked Oct 20 '25 10:10

Colin M. Lynch


1 Answers

One can manually define a vector of desired breaks points and then pass the vector to the "breaks" option in the geom_contour_filled() function.

In the below script, finds 8 break intervals between the grand minimum and the grand maximum of the dataset.

Also there are 2 functions defined to create the palette and label names for the legend.

 #establish the min and max of scale 
grandmin <- min(z1, z2)-1
grandmax <- max(z2, z2)

#define the number of breaks.  In this case 8 +1 
mybreaks <- seq(grandmin, ceiling(round(grandmax, 0)), length.out = 9)
#Function to return the dersired number of colors
mycolors<- function(x) {
   colors<-colorRampPalette(c("darkblue", "yellow"))( 8 )
   colors[1:x]
}

#Function to create labels for legend
breaklabel <- function(x){
   labels<- paste0(mybreaks[1:8], "-", mybreaks[2:9])
   labels[1:x]
}

ggplot(data, aes(x, y, z = z1)) +
   geom_contour_filled(breaks= mybreaks, show.legend = TRUE) +
   scale_fill_manual(palette=mycolors, values=breaklabel(8), name="Value", drop=FALSE) +
   theme(legend.position = "right")

ggplot(data, aes(x, y, z = z2)) +
   geom_contour_filled(breaks= mybreaks, show.legend = TRUE) +
   scale_fill_manual(palette=mycolors, values=breaklabel(8), name="Value", drop=FALSE) 

enter image description here

like image 188
Dave2e Avatar answered Oct 23 '25 02:10

Dave2e