7

I drew two contour plots, one by matplotlib and the other by plotly. I want to add more contour lines to the plot. In the case of matplotlib, there was no poblem. But regarding to plotly, I have no idea how to change the number of contour lines. Below is my code.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn') 
import math

x = np.linspace(-np.pi, np.pi, num=50)
y = x

def pf(a, b):
    return math.cos(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])

# contour plot using matplotlib
cp = plt.contour(x, y, f, 45, cmap='viridis')
plt.clabel(cp, inline=1, fontsize=10);

enter image description here

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Contour(z=f, x=x, y=y, contours_coloring='lines', line_width=1,
                         contours={"showlabels":True, "labelfont":{"size":12, "color":'green'}}))

fig.update_layout(
       {"title": {"text": "<b>Contour Plot with Plotly</b>", "x": 0.5, "y": 0.85, "font": {"size": 15} },
        "showlegend": True,
        "xaxis": {"title": "x axis", "showticklabels":True, "dtick": 1},
        "yaxis": {"title": "y axis", "showticklabels": True, "dtick": 1},
        "autosize":False,
        "width":600,
        "height":450})

fig.show()

enter image description here

yannvm
  • 418
  • 1
  • 4
  • 12
Kimshine
  • 79
  • 3

1 Answers1

0

You can adjust the level of detail of the contour plot with the ncontours parameter.

Code

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


#Create data
x = np.linspace(-np.pi, np.pi, num=50)
y = x

def pf(a, b):
    return math.cos(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])

#Create plot
fig = go.Figure()
fig.add_trace(go.Contour(z=f, x=x, y=y, contours_coloring='lines', 
                         line_width=1,contours={"showlabels":True, 
                         "labelfont":{"size":12, "color":'green'}}))

#Adjust the number of coutour levels
fig.update_traces(ncontours=45, selector=dict(type='contour'))
fig.show()

Output

Detailed Plotly contour plot V1

Other method

It is also possible to modify the coutour_size parameter of the trace to adjust the step between each contour level. To do so you also need to specify the contour_start and contour_end of the plot.

#Create plot
fig = go.Figure()
fig.add_trace(go.Contour(z=f, x=x, y=y, contours_coloring='lines', 
                         line_width=1,contours={"showlabels":True, 
                         "labelfont":{"size":12, "color":'green'}}))

#Adjust the number of coutour levels
fig.update_traces(contours_start=-1, contours_end=1, contours_size=0.1)
fig.show()

Detailed Plotly contour plot V2

yannvm
  • 418
  • 1
  • 4
  • 12