Search code examples
pythonmatplotlibpython-typing

How to type-hint a matplotlib Figure object in Python3


I am trying to add type hints for data returned by plt.subplots. That works fine for plt.Axes, but I can't seem to find a solution for Figure.

Any ideas what I could do?

An abbreviated version of my code is:

def draw_graph() -> Tuple[plt.Figure, plt.Axes]: 

    fig, ax = plt.subplots(figsize=(14,10))
    return (fig, ax)

I get the message: "Figure" is not a known member of module Pylance


Solution

  • With the latest Matplotlib (v3.7.1) I was able to do the following:

    import matplotlib.pyplot as plt
    import matplotlib.figure
    
    def draw_graph() -> Tuple[matplotlib.figure.Figure, plt.Axes]: 
    
        fig, ax = plt.subplots(figsize=(14,10))
        return (fig, ax)
    

    I haven't tested using plt.Figure, but my IDE (i.e., VS Code) was not giving me any errors with plt.Figure.