0

Recently I attempted using seaborn to produce a contour plot. The only related function, kdeplot, seemingly only allows to visualize density of data, and it is not possible to provide custom z-index information.

Let me illustrate on a toy example: we have a function f with two independent variables x, y and a dependent variable z.

def f(x: float, y: float) -> float:
    return x * y

I would like to construct a contour plot on [0,1] \times [0,1].

Specifically in my case, I was trying to align multiple such plots in seaborn FacetGrid.

Let me know your experience in my case.

In pure matplotlib, the single contour plot can be implemented as follows.

import itertools
import matplotlib.pyplot as plt
import numpy as np

# construct grid
N = 1000  # granularity
grid = np.linspace(0, 1, N, dtype='float32')

# evaluate function
z = map(lambda i: f(*i), itertools.product(grid, grid))

# plot
plt.contourf(
    grid,
    grid,
    np.array(list(z)).reshape((N, N)),
    100,
)
plt.show()

It is possible to embed matplotlib plots in seaborn FacetGrid, but I needed various workarounds to get even the most basic customizations of the facet. Several features I dealth with: custom ticks, unified styling (palette), shared color map, placing color bar.

At the end, I re-did everything using subfigures in matplotlib only, dropping seaborn. I would have no problem, if kdeplot allowed specifying custom z-index information.

Conclusions

  • It is not possible to produce contour plot in seaborn with provided z-index information.
  • Working with matplotlib plots in seaborn FacetGrid is possible, but becomes very nasty.

I don't want this to sound like criticism of seaborn. I genuinely love the package, it squeezes so much of matplotlib and is so easy to use. I am just annoyed about the limitations I encountered in my case.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Martin Benes
  • 265
  • 10
  • seaborn is a high-level api for matplotlib; a facetgrid is matplotlib subplots. There is little point in contorting your data / code to work with the seaborn API. In this case, working directly with the matplotlib explicit “Axes” interface, seems to be the best option. – Trenton McKinney Jun 19 '23 at 14:48

0 Answers0