SiH
SiH

Reputation: 1546

Setting color levels in contourplots in ggplot R

I am plotting contour plots using ggplot in loop. I have few concerns -

  1. the color levels are different in all iterations, how do it keep it steady iterations?

  2. the number and range of levels are also changing with iteration, how to keep it constant across iterations ?

  3. the length occupied by color scale is much longer than actual figure. How do I adjust that ?

  4. How do I manually set the levels of colors in contours?

I have attached a sample below. Can someone please edit in the same code with comments

library(tidyverse)
library(gridExtra)
library(grid)

# data generation
x <- seq(-10, 10, 0.2)
y <- seq(-10, 10, 0.2)
tbl <- crossing(x, y)

for (i in seq(1, 2)) # to create two sample plots
{
  # initialize list to store subplots
  p <- list()
  
  for (j in seq(1, 3)) # to create 3 subplots
  {
    # for randomness
    a <- runif(1)
    b <- runif(1)
    
    # add z
    tbl <- tbl %>%
      mutate(z = a*(x - a)^2 + b*(y - b)^2)
    
    # plot contours
    p[[j]] <- ggplot(data = tbl,
                aes(x = x,
                    y = y,
                    z = z)) +
      geom_contour_filled(alpha = 0.8) + 
      theme_bw() + 
      theme(legend.position = "right") + 
      theme(aspect.ratio = 1) +
      ggtitle("Sample")
    

  }
  
  p <- grid.arrange(p[[1]], p[[2]], p[[3]],
                    ncol = 3)
  
  ggsave(paste0("iteration - ", i, ".png"),
         p, 
         width = 8,
         height = 3)
}

The actual plots are subplot for another plot, so I can increase its size. Therefore, width and height cannot be increased in ggsave.

Thanks

Upvotes: 0

Views: 766

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

You can set breaks in geom_contour_filled. You can change your pngs by doubling their size but halfing their resolution. They will remain the same in terms of pixel dimensions.

for (i in seq(1, 2)) # to create two sample plots
{
  p <- list()
  
  for (j in seq(1, 3)) # to create 3 subplots
  {
    # for randomness
    a <- runif(1)
    b <- runif(1)
    
    tbl <- tbl %>%
      mutate(z = a*(x - a)^2 + b*(y - b)^2)
    
    p[[j]] <- ggplot(data = tbl,
                aes(x = x,
                    y = y,
                    z = z)) +
      geom_contour_filled(alpha = 0.8, breaks = 0:9 * 20) + 
      scale_fill_viridis_d(drop = FALSE) +
      theme_bw() + 
      theme(legend.position = "right") + 
      theme(aspect.ratio = 1) +
      ggtitle("Sample")
  }
  
  p <- grid.arrange(p[[1]], p[[2]], p[[3]],
                    ncol = 3)
  
  ggsave(paste0("iteration - ", i, ".png"),
         p, 
         width = 16,
         height = 6,
         dpi = 150)
}

iteration-1.png

enter image description here


iteration-2.png enter image description here

Upvotes: 2

Related Questions