Black Lives Matter. Please consider donating to Black Girls Code today.

geom_contour in ggplot2

How to make a contour in ggplot2 using geom_contour.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Basic geom_contour plot

geom_contour produces a similar output to geom_density_2d, except it uses a third variable for the values rather than frequency. The volcano dataset comes pre-loaded on R.

library(plotly)
library(reshape2)
df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2, z= value)) +
  geom_contour() +
  scale_fill_distiller(palette = "Spectral", direction = -1)
fig <- ggplotly(p)

fig

Coloured Plot

See here for a list of colour palettes that come with the brewer (discrete) and distiller (continuous) packages.

library(plotly)
library(reshape2)
df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2, z= value, colour=stat(level))) +
  geom_contour() +
  scale_colour_distiller(palette = "YlGn", direction = 1)

ggplotly(p)

Filled Plot

It's possible to colour in each of the layers, by changing geom_contour to stat_contour as below. As the edges of the graph indicate, filled contour plots only work when each layer is an enclosed shape rather than an open line; a geom more suited to this functionality would be geom_tile or geom_raster.

library(plotly)
library(reshape2)
df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2, z= value)) +
  stat_contour(geom="polygon",aes(fill=stat(level))) +
  scale_fill_distiller(palette = "Spectral", direction = -1)

ggplotly(p)

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)