Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Bug]: Saving a figure with indicate_inset_zoom to pdf and then pickling it causes TypeError #27805

Closed
@lmarti-dev

Description

@lmarti-dev

Bug summary

If a fig with an ax using the indicate_inset_zoom is saved to pdf and then pickled, one gets the following error:

TypeError: cannot pickle '_io.BufferedWriter' object

Code for reproduction

import pickle
import matplotlib.pyplot as plt


def plot(inset_zoom: bool, format: str):
    fig, ax = plt.subplots()
    ax.plot(
        [1, 1],
        [2, 2],
    )

    if inset_zoom:
        ax.indicate_inset_zoom(ax)

    if format is not None:
        fig.savefig(f"./test1.{format}", format=f"{format}")

    pickle.dumps(fig)


for format in (None, "png", "pdf"):
    for inset_zoom in (False, True):
        print(f"format: {format} inset_zoom {inset_zoom}")
        plot(inset_zoom, format)
        print("ok")

Actual outcome

(venv) C:\Users\Moi4\Desktop\code\test\pickle_buffwr_err>python error_with_mpl_pickle.py
format: None inset_zoom False
ok
format: None inset_zoom True
ok
format: png inset_zoom False
ok
format: png inset_zoom True
ok
format: pdf inset_zoom False
ok
format: pdf inset_zoom True
Traceback (most recent call last):
  File "C:\Users\Moi4\Desktop\code\test\pickle_buffwr_err\error_with_mpl_pickle.py", line 24, in <module>
    plot(inset_zoom, format)
  File "C:\Users\Moi4\Desktop\code\test\pickle_buffwr_err\error_with_mpl_pickle.py", line 18, in plot
    pickle.dumps(fig)
TypeError: cannot pickle '_io.BufferedWriter' object

Expected outcome

The expected outcome would be no TypeError

Additional information

Saving to pickle before saving the figure is a workaround.

Operating system

Windows 10

Matplotlib Version

3.7.1 and 3.8.3

Matplotlib Backend

TkAgg

Python version

3.10.11

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: pickleIssues to do with pickling

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions