Search code examples
pythonjupyter-notebook

Using mathplotlib in jupyter lab causes kernel to die


Using matplotlib.pyplot to create a figure works on a local python project, but in a jupyter lab enviroment, with the same code, it causes the kernel to die.

Older issues suggested downgrading freetype from 2.11 to 2.10.

But I use version 2.12.1 in both the pycharm and de jupyter version of the project, but 1 works and the other doesn't. this doesn't seem to be the solution.

Others also suggested trying:

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

This wasn't the solution either

my code:

import tensorflow as tf
import pathlib
import matplotlib.pyplot as plt
import numpy as np

batch_size = 32
img_height = 180
img_width = 180

data_dir = pathlib.Path("./data_dir").with_suffix('')
output_dir = pathlib.Path("./ds_out").with_suffix('')

ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  labels='inferred',
  image_size=(img_height, img_width),
  batch_size=batch_size)

class_names = ds.class_names
print(class_names)

ds.save(str(output_dir))

loaded_ds = tf.data.Dataset.load(str(output_dir))

plt.figure(figsize=(10, 10))
for images, labels in loaded_ds.take(1):
  for i in range(9):
    ax = plt.subplot(3, 3, i + 1)
    plt.imshow(images[i].numpy().astype("uint8"))
    plt.title(class_names[labels[i]])
    plt.axis("off")

plt.show()

Edit: I tried a simpler example in a new notebook:

# importing matplotlib module 
from matplotlib import pyplot as plt 
 
# x-axis values 
x = [5, 2, 9, 4, 7] 
 
# Y-axis values 
y = [10, 5, 8, 4, 2] 
 
# Function to plot 
plt.plot(x, y) 
 
# function to show the plot 
plt.show()

This also kills the kernel unless I remove both these lines:

# Function to plot 
plt.plot(x, y) 
     
# function to show the plot 
plt.show()

Solution

  • None of the regular fixes worked for me, so I decided to try again.

    I created a fresh venv, and from that a new ipython kernel, and used that kernel in jupyterlab.

    The issue is fixed by circumventing the old kernel, but it is weird that I did the same thing twice and on one it works and in the other it doesn't.