Plotly Contour Plot – A Complete Guide

Plotly-contour-title.png

In this article, we will be going to learn about the Plotly library for Python and the various ways through which fascinating contour plots can be created. We will be looking at various examples of contours plots with detailed code analysis for each example. We will also be learning multiple ways to customize one’s contour plot. So, let’s start with the basics.

What is a contour plot?

plotlybasic-plot.png

Contours are a two-dimensional depiction of a three-dimensional surface, complete with joints and curves. It’s drawn with the help of a contour function (Z), which is a function of two variables (the X-axis and Y-axis coordinates).

Also read: Matplotlib Contour Plots – A Complete Reference

What is Plotly library?

Plotly offers various data visualization libraries to plot charts and graphs. We can choose from a huge set of plotting libraries, and tools dedicated to creating various different types of charts available out there. In this article, we will mostly be working with a single import package and only a single plot function. That’s the ease of use we get while using Plotly.

Installing Plotly

To install Plotly in your system, type the command:

Pip install plotly==5.5.0 

Creating Contour Plots with Plotly

Let’s get into the creation of these contour plots with Plotly.

Basic contour plots

To start with, we will be plotting a simple contour plot using Plotly. The very first thing required is the import libraries.

The import package below is like a universal Plotly syntax, that gets most of the job done.

import plotly.graph_objects as grob

Plotly contour function

The contour function use initialized data to make plots. We have to provide the x,y coordinates and the z function to it.

There are two parts to create a contour plot: Data initialization and Object Creation using the contour function and there are multiple different ways to do both, every method affects the contour. To keep things simple, let’s assume that our coordinates are initialized with the variable ‘data’.

As seen below, the code tells the compiler to take values of data for the z function of the contour.

grid_fig = grob.Figure(data =
	grob.Contour(z = data))

Let’s look at a few program examples to understand all the methods.

Plotly Contour Plot with a coordinate array as z-function:

import plotly.graph_objects as grob

# This 5X5 matrix stores the coordinate values required for z function
data = [[6, 4, 5, 5, 6],
	[1, 5, 5, 4, 6],
	[5, 4, 4, 6, 4],
	[7, 8, 4, 3, 3]]

grid_fig = grob.Figure(data =
	grob.Contour(z = data))

grid_fig.show()

Output:

plotlybasic-plot.png

Plotly Contour Plot with specific X,Y,Z values

import plotly.graph_objects as grob

fig = grob.Figure(data =
    grob.Contour(

        z=[[10, 10.625, 12.5, 15.625, 20],
           [5.625, 6.25, 8.125, 11.25, 15.625],
           [2.5, 3.125, 5., 8.125, 12.5],
           [0.625, 1.25, 3.125, 6.25, 10.625],
           [0, 0.625, 2.5, 5.625, 10]],

        x=[-3, -2, -1, 0, 1], # horizontal axis
        y=[0, 1, 3, 4, 5] # vertical axis
    ))
fig.show()

Output:

Plotly-coordinates_xyz.png

Here the z function is a coordinate array similar to the previous example. Using the Numpy import package further allows us to use more complex data for our contour plots. In the next example, we will observe how we can put a trigonometric identity for our z function.

Contour Plot using Numpy

import plotly.graph_objects as grob
import numpy as nump

# variables are initialised with x,y co-ordinates
cordof_x = nump.arange(0, 23, 0.5)
cordof_y = nump.arange(0, 46, 0.3)

# A mesh is created with the given co-ordinates by this numpy function
[X, Y] = nump.meshgrid(cordof_x, cordof_y)

contour_function = nump.cos(X*(1/8)) + nump.sin(Y*(1/16))

contour_plot = grob.Figure(data =
	grob.Contour(x = cordof_x, y = cordof_y, z = contour_function))

contour_plot.show()

Output:

Plotly-numpy-plot.png

It is hoped that the above examples would have made it completely clear how basic contour plots are created. Thus far we have learned the different methods of creating inputs and z functions for our contour plot. Now, we will venture towards the styling aspects of our contour plots.

Customizing Plotly Contour Plots

In this section of the article, we will mainly address the front-end aspects or simply the styling aspects of our contour plots.

Setting the color and scale of plots

Let’s take an example of a program where we have a coordinate array initialized to the z function. Now, in our contour plot, if we want to represent our plot with a custom scale, we can do that by:

dx=40,
x0=10,
dy=10,
y0=20,

Now after the scale is set, let’s suppose we want to change the theme of our plot. We can do that by:

colorscale='hot',

OR

colorscale='electric',

To add some final touches, we can also add a color scale to our plot. That can be done by:

contours=dict(
            start=0,
            end=14,
            size=2,
        ),

Let’s put everything in a program, and observe how it plays out.

import plotly.graph_objects as grob

grid_fig = grob.Figure(data =
    grob.Contour(
        z=[[10, 10.625, 12.5, 15.625, 20],
           [5.625, 6.25, 8.125, 11.25, 15.625],
           [2.5, 3.125, 5., 8.125, 12.5],
           [0.625, 1.25, 3.125, 6.25, 10.625],
           [0, 0.625, 2.5, 5.625, 10]],
        dx=40,
        x0=10,
        dy=10,
        y0=20,
        colorscale='electric',
        contours=dict(
            start=0,
            end=14,
            size=2,
        ),
     ))

grid_fig.show()

Output:

plotly-custom_plot.png

Creating an advanced contour plot

Till now, we have learned about the basic aspects of contour plots using Plotly. Now we will put together everything we have learned so far to create an advanced contour plot so that we can understand how contour plots created for real-life applications are.

Code Below:

import numpy as np
import math
import plotly.graph_objects as grob


x = np.linspace(-np.pi, np.pi, num=80)
y = x
def pf(a, b):
    return math.sin(b) / (1 + a**2)
f = np.empty((len(x), len(y)))

for i in range(len(x)):
    for j in range(len(y)):
        f[i,j] = pf(x[i], y[j])

grid_fig = grob.Figure()
grid_fig.add_trace(grob.Contour(z=f, x=x, y=y,
                         contours_coloring='lines',
                         line_width=1.5,
                         contours={"showlabels":True,
                                   "labelfont":{"size":10,
                                                "color":'red'}}))

grid_fig.update_layout(

{   "title": {"text": "<b>Advanced Contour Plot</b>", "x": 0.5, "y": 0.9, "font": {"size": 14} },
    "showlegend": True,
    "xaxis": {"title": "scale of x ----------------------->", "showticklabels":True, "dtick": 1},
    "yaxis": {"title": "scale of y ------------>", "showticklabels": True, "dtick": 1},
    "autosize":False,
    "width":1200,
    "height":600})

grid_fig.show()

Output:

Plotly-advanced_plot.png

Conclusion

We have learned in this article about the basic concepts of Plotly and how it can be customized as per our needs. We understood how we can use both specific coordinate values or coordinate arrays for our input methods and how the integration of numpy allows contour plotting of trigonometric functions as well. At last, we also observed how to code an advanced plot. Hope this article helped you in learning and understanding Plotly better.