Plotly: How to change scale of the contour lines using go.Contour?

Viewed 413

I'm trying to plot 3d ravine functions using contour lines from plotly. Here is my code:

def draw_plots(f, x, y, history=None, n_lines=100, line_width=50, n_points_along_axis=500):
  X = np.linspace(x[0], x[1], n_points_along_axis)
  Y = np.linspace(y[0], y[1], n_points_along_axis)
  if history is None:
    trace = go.Scatter(
      x=[], 
      y=[],
      mode='lines',
      marker = dict(
          color="rgba(255, 255, 255, .6)"
      )
    )
  else:
    history = np.array(history)
    trace = go.Scatter(
      x=history[:, 0], 
      y=history[:, 1],
      
      marker = dict(
          color="rgba(255, 255, 255, .6)"
      )
    )
  contour = go.Contour(x=X, y=Y, z=[[f([x, y]) for x in X] for y in Y], contours=dict(start=0, end=line_width*n_lines, size=line_width))
  fig = go.Figure(data=[trace, contour])
  fig.show()

Here is an example f(x,y) = (y−x^2)^2+ (1−x)^2 (white line here is a visualization for my optimization algorithm)

So, the problem is that I didn't find a way to change scale of the lines. It is fixed to some number, but as the function is very steep it will be more informative if it is drawn with logscale for example.

1 Answers

You can set scale for the y-axis of a go.Figure() object using:

fig.update_yaxes(type="log")

Here's a standard go.Contour() plot from the plotly docs:

enter image description here

And here's the same setup with the scale of the y-axis set to log:

enter image description here

At least their appearances differ, but I'm not sure if it will be suitable for you use-case. Note that you can do the same thing with the x-axis using fig.update_xaxes(type="log") to get:

enter image description here

Complete code:

import plotly.graph_objects as go

fig = go.Figure(data =
    go.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]]
    ))

fig.update_yaxes(type="log")
fig.show()
Related