SiH
SiH

Reputation: 1546

plot contours in ggplot

How do I plot contours ?

I have x, y, z. I wish to plot contour lines using V values.

# data
tbl <- tibble(x = runif(n = 1000, min = 0, max = 1),
              y = runif(n = 1000, min = 0, max = 1),
              V = x^2.5 + y^2)

# plots
ggplot(data = tbl, 
       aes(x = x,
           y = y
           z = V)) + 
  geom_contour_filled(alpha = 0.8, breaks = seq(0, 2, 0.2)) +
  theme_bw()


Upvotes: 1

Views: 1047

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76683

Here is a way, solving the problem with a shameless copy&paste of the franke example in the documentation of geom_contour_filled.

The trick is to use package interp to prepare the data for plotting. In the code below the only change in the instruction to create grid is the data set being binned.

suppressPackageStartupMessages({
  library(tidyverse)
  library(interp)
})

set.seed(2022)
tbl <- tibble(x = runif(n = 1000, min = 0, max = 1),
              y = runif(n = 1000, min = 0, max = 1),
              V = x^2.5 + y^2)
grid <- with(tbl, interp::interp(x, y, V))
griddf <- subset(data.frame(x = rep(grid$x, nrow(grid$z)),
                            y = rep(grid$y, each = ncol(grid$z)),
                            z = as.numeric(grid$z)),
                 !is.na(z))

# plots
ggplot(data = griddf,
       aes(x = x,
           y = y,
           z = z)) + 
  stat_contour_filled(alpha = 0.8, breaks = seq(0, 2, 0.2)) +
  theme_bw()

Created on 2022-05-18 by the reprex package (v2.0.1)


Edit

To better control the bins, use either argument bins or argument binwidth instead of breaks. The following code has a bin width of 0.1, doubling the number of bins and now uses geom_contour_filled, like in the question.

ggplot(data = griddf,
       aes(x = x,
           y = y,
           z = z)) + 
  geom_contour_filled(alpha = 0.8, binwidth = 0.1, show.legend = FALSE) +
  theme_bw()

Created on 2022-05-18 by the reprex package (v2.0.1)

Upvotes: 2

Related Questions