Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Visualization
  • Statistics in R
  • Machine Learning in R
  • Data Science in R
  • Packages in R
  • Data Types
  • String
  • Array
  • Vector
  • Lists
  • Matrices
  • Oops in R
Open In App
Next Article:
How to Add Constant Line to Animated Plot in Plotly?
Next article icon

How to Add a permanent contour line to a surface plot in R plotly

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A surface plot is a 3D plot that displays a surface in a three-dimensional space. It is a useful visualization technique for representing mathematical functions or data with two continuous variables. A contour line, on the other hand, is a line that connects points of equal value in a two-dimensional plot. Adding a contour line to a surface plot can enhance its visualization by highlighting the areas of equal value on the surface.

The plotly library in R provides an easy way to create surface plots with customizable contour lines. In this article, we will explain the theory behind adding a permanent contour line to a surface plot using the plotly library, and provide 3-4 examples of R code with detailed explanations.

A surface plot in R Plotly is a three-dimensional plot that represents a function of two input variables (usually, x and y) and one output variable (usually, z). The plot shows the surface of this function as a mesh of triangles, with the height of each triangle representing the value of the output variable.

A contour line, on the other hand, is a curve that connects points of equal value on the surface plot. These lines are useful for visualizing the shape and structure of the function, as well as for identifying areas of interest or anomalies in the data.

To add a permanent contour line to a surface plot in R Plotly, we can use the contours argument in the plot_ly() function. This argument allows us to specify the contour levels we want to show, as well as various properties of the contour lines such as their width and color.

By setting the contours argument to list(z = list(show = TRUE, width = 2, coloring = "lines")), we can add contour lines to the plot that connect points of equal value on the surface. We can adjust the appearance of the contour lines by specifying their width and coloring properties. For example, we can set width = 2 to make the lines thicker, or coloring = "heatmap" to color them based on the heatmap color scale of the surface plot.

In addition, we can also set the highlightcolor property to change the color of the contour line at the value of interest. This can be useful for highlighting specific features or anomalies in the data.

Overall, adding a permanent contour line to a surface plot in R Plotly is a simple yet powerful way to enhance the visualization and gain deeper insights into the underlying data.


To add a permanent contour line to a surface plot using plotly, we need to use the add_trace() function to add a contour trace to the plot. The add_trace() function allows us to add additional traces to a plot created using the plot_ly() function. A trace is a set of data and visual properties that are used to create a plot.

The add_trace() function takes several parameters, including the data and visual properties of the trace. In the context of adding a permanent contour line to a surface plot, we need to set the type parameter to "contour" and provide the z values for the contour line. We can also customize the appearance of the contour line using the contours parameter.

Example 1: Basic Surface Plot with Contour Line
In this example, we will create a basic surface plot with a permanent contour line at a fixed height using the plotly library in R. Here is the code:

R
library(plotly)  # Create a surface plot p <- plot_ly(z = volcano, type = "surface")  # Add a contour trace with a fixed z value p <- add_trace(p, z = matrix(120, nrow = nrow(volcano), ncol = ncol(volcano)), contours = list(coloring = "none"))  # Show the plot p 

Output:

 

In this code, we first load the plotly library using the library() function. We then create a surface plot of the volcano dataset using the plot_ly() function. The z parameter is set to volcano, which is a matrix of altitude values. The type parameter is set to "surface" to create a surface plot.

We then add a contour trace to the plot using the add_trace() function. The z parameter is set to a matrix with a fixed value of 120, which represents the height of the contour line. The contours parameter is used to customize the contour line by setting coloring to "none", which means that the contour line will have a single color.

Finally, we show the plot using the p object.

Example 2: Surface Plot with Customized Contour Line

In this example, we will create a surface plot with a customized contour line using the plotly library in R. Here is the code:

R
library(plotly)  # Create a surface plot with a dynamic contour line p <- plot_ly(z = volcano, type = "surface", contours = list(z = list(show = TRUE)))  # Show the plot p 

Output:

 

In this code, we first load the plotly library using the library() function. We then create a surface plot of the volcano dataset using the plot_ly() function. The z parameter is set to volcano, which is a matrix of altitude values. The type parameter is set to "surface" to create a surface plot.

We then add a dynamic contour line to the plot using the contours parameter in plot_ly(). The z parameter in contours is set to list(show = TRUE) to show the contour lines. This will create a default number of contour lines based on the range of the z values.

Finally, we show the plot using the p object.

Note that we did not use the add_trace() function in this code because we added the surface trace and the contour lines together using the contours parameter in plot_ly(). This is what makes the contour lines dynamic because they are based on the z values of the surface plot.

Adding features to make more attractive:

R
library(plotly)  # Create a surface plot with a dynamic contour line p <- plot_ly(z = volcano, type = "surface", colors = "Blues",               colorbar = list(title = "Elevation", len = 0.5),               contours = list(z = list(show = TRUE, width = 2,                                        highlightcolor = "#ff0000",                                         project = list(z = TRUE)),                               coloring = "heatmap"))  # Set the plot layout p <- layout(p, title = "Volcano Surface Plot with Dynamic Contour Lines",             scene = list(xaxis = list(title = "X-axis"),                          yaxis = list(title = "Y-axis"),                          zaxis = list(title = "Elevation"),                          aspectratio = list(x = 1, y = 1, z = 0.5)))  # Show the plot p 

Output:

 

In this code, we have added the following features to the surface plot with dynamic contour lines:

colors: The colors parameter is set to "Blues" to change the color scheme of the surface plot to shades of blue.

colorbar: The colorbar parameter is used to add a color bar to the plot with a title and a custom length of 0.5.

width: The width parameter in contours is set to 2 to increase the width of the contour lines.

highlightcolor: The highlightcolor parameter in contours is set to "#ff0000" to highlight the contour lines in red.

project: The project parameter in contours is set to list(z = TRUE) to project the contour lines onto the z-axis.

coloring: The coloring parameter in contours is set to "heatmap" to color the contour lines based on the color scale of the surface plot.

We have also set the layout of the plot using the layout() function. The title parameter is used to add a title to the plot, and the scene parameter is used to customize the x-axis, y-axis, and z-axis of the plot. The aspectratio parameter is used to set the aspect ratio of the plot to 1:1:0.5.

Finally, we show the plot using the p object.

Conclusion:

adding a permanent contour line to a surface plot in R Plotly can greatly enhance the visualization of the underlying data and help identify important features and anomalies. This can be achieved by using the contours argument in the plot_ly() function and specifying the contour levels, width, coloring, and highlight color properties. With this simple technique, we can create a more informative and visually appealing plot that can be used for a variety of applications, from scientific research to data exploration and communication.


Next Article
How to Add Constant Line to Animated Plot in Plotly?

H

honeyj
Improve
Article Tags :
  • R Language

Similar Reads

  • How to Add Constant Line to Animated Plot in Plotly?
    Animated plots are a useful way to visualize data over time or to highlight the relationship between different variables. In this article, we will learn how to create animated plots using the plot_ly() function in R Programming Language. To create an animated plot in R, we will use the plot_ly() fun
    2 min read
  • How to Add an Average Line to Plot in Matplotlib
    In this article, we will learn how we can add an average line to a plot in matplotlib. We will discuss the steps to add a horizontal average line using the axhline function, as well as the steps to add a vertical average line using the axvline function in Matplotlib. Throughout the article, we will
    6 min read
  • How to do 3D line plots grouped by two factors with the Plotly package in R?
    Plotly is a powerful library for making interactive charts. We will be able to plot 3D line plots using Plotly that can be utilized to analyze complex data and display results in a clear manner. Syntax: plot_ly(data, x = ~x, y = ~y, z = ~z, type = "scatter3d", mode = "lines") Parameters: data: The d
    3 min read
  • How to plot a dashed line in matplotlib?
    Matplotlib is used to create visualizations and plotting dashed lines is used to enhance the style and readability of graphs. A dashed line can represent trends, relationships or boundaries in data. Below we will explore how to plot and customize dashed lines using Matplotlib. To plot dashed line: S
    2 min read
  • How to Make Lines of Radar Chart Round in R Using Plotly
    The Radar chart is used to represent multivariate independent data graphically. It's a circular chart where each independent variable has its own axis and all those axes are merged at the center of the radar chart. It is also known as Web Chart because it looks like Spider Web. This chart is used wh
    3 min read
  • How To Add Mean Line to Ridgeline Plot in R with ggridges?
    In this article, we will discuss how to add a mean line to the Ridgeline plot in R Programming Language with the ggridges package.  Ridgeline plot helps us to visualize multiple distributions or a distribution that changes a quantifiable variable. The name “ridgeline” comes from its appearance as an
    3 min read
  • How can I save a plot as an image on the disk in R?
    In data analysis and visualization, saving the plots as images can be crucial for documentation, reporting, and sharing the results with others. R is a powerful programming language and it can offer various ways to create and save plots. One of the popular packages for creating the plots in the R is
    3 min read
  • How to Install plotly in Anaconda for R
    The Plotly is a powerful and versatile graphing library that allows users to create interactive, publication, and quality graphs. Plotly is a popular library for building interactive graphs and visualizations in R Programming Language. When using Anaconda, a distribution of Python and R for scientif
    2 min read
  • How to put text on different lines to ggplot2 plot in R?
    ggplot2 is a plotting package in R programming language that is used to create complex plots from data specified in a data frame. It provides a more programmatic interface for specifying which variables to plot onto the graphical device, how they are displayed, and general visual properties.  In thi
    3 min read
  • How to Plot Multiple Series/Lines in a Time Series Using Plotly in R?
    Plotly is a powerful and flexible graphing library that enables the creation of interactive plots in R. It is especially useful for visualizing time series data with multiple lines or series. In this article, we will cover how to plot multiple time series in a single plot using Plotly in R. Multiple
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences