logo

How to Solve the "Fail to create pixmap with TK_GetPixmap in TKImgPhotoInstanceSetSize" Error in Python matplotlib 📂Programing

How to Solve the "Fail to create pixmap with TK_GetPixmap in TKImgPhotoInstanceSetSize" Error in Python matplotlib

Problem

import matplotlib.pyplot as plt
import numpy as np

for i in range(400):
    fig = plt.figure(figsize=(12, 12))
    plt.plot(np.random.rand(10))
    plt.savefig("./plt_test/no_%d" %i)
    print("test_%d" %i)

Let’s say you are running a code in Python using matplotlib.pyplot to draw a graph and save it, like the one above. The moment you generate the 369th figure, the following error occurs in the output window.

test_366
test_367
test_368
Fail to create pixmap with TK_GetPixmap in TKImgPhotoInstanceSetSize

This error does not occur when running on Colab, but only when running locally. Since the error always occurs at the 369th figure, it seems that creating too many figures is the cause, but the problem is not solved even if you use plt.close() to close the window each time. It seems that it is impossible to create the 369th figure, regardless of whether the window is closed or not.

Solution

Then, the solution is simple. As shown below, you take the part where the figure is created out of the for loop, create the figure only once. Then, by drawing and erasing the graph on it repeatedly, the above error does not occur.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(12, 12))

for i in range(400):
    plt.plot(np.random.rand(10))
    plt.savefig("./plt_test/no_%d" %i)
    plt.clf()
    print("test_%d" %i)

Environment

  • OS: Windows10
  • Version: Python 3.9.2, matplotlib 3.4.2