OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

RuntimeError: In set_size: Could not set the fontsize (invalid ppem value; error code 0x97) In Google Colab (Matplotlib issue)

  • Thread starter Thread starter Jane
  • Start date Start date
J

Jane

Guest
I have some complex code that I need to run in Google Colab (students will use this for a test). I reproduced my error in a smaller piece of code, i try to create a simple heatmap. I already set the font to the Colab default (monospace) and sepcified a font size. Also DPI was adjusted to avoid the error.

Code:
import matplotlib.pyplot as plt
import numpy as np
import csv
import time

# Clear the font cache and set font settings
import matplotlib as mpl
mpl.font_manager._load_fontmanager()
plt.rcParams['font.family'] = 'monospace'
plt.rcParams['font.size'] = 10

# Start time
t_start = time.time()

# Example data for testing
np.random.seed(0)
L_dataset = np.random.rand(10, 10) * 100  # Random data between 0 and 100

# Transform list to array
A_dataset = np.array(L_dataset, dtype=np.float32)

try:
    # Set the figure size in inches and specify DPI
    plt.figure(figsize=(11, 8), dpi=100)
    
    # Create heat map
    fig, ax = plt.subplots()
    cax = ax.matshow(A_dataset, cmap='OrRd', vmin=0, vmax=100)
    
    # Add colorbar
    fig.colorbar(cax)
    
    # Set tick marks for grid lines
    ax.set_xticks(np.arange(-.5, len(A_dataset[0]), 1), minor=True)
    ax.set_yticks(np.arange(-.5, len(A_dataset), 1), minor=True)
    
    # Gridlines based on minor ticks
    ax.grid(which='minor', color='white', linestyle='-', linewidth=2)
    
    # Loop to annotate each cell with its value
    for i in range(A_dataset.shape[0]):
        for j in range(A_dataset.shape[1]):
            ax.text(j, i, '{:0.2f}'.format(A_dataset[i, j]), ha='center', va='center', color='white')
    
    plt.grid(which='both', color='white', linestyle='-', linewidth=0)  # Optional: add grid lines
    plt.title('Heatmap of A_dataset')
    
    # Save the plot as a PNG image in the "dir" directory
    filename = 'HeatMap.png'
    plt.savefig(filename, dpi=300, bbox_inches='tight')
    plt.clf()  # clear the figure to start with a new blank figure

except RuntimeError as e:
    print(f"RuntimeError: {e}")

# End and print time
print('Time elapsed for running module "N_VA_HeatMap": {:.3f} sec.'.format(time.time() - t_start))

The error I get is:

Code:
RuntimeError: In set_size: Could not set the fontsize (invalid ppem value; error code 0x97)
Time elapsed for running module "N_VA_HeatMap": 1.611 sec.
<Figure size 1100x800 with 0 Axes>
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/IPython/core/formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

19 frames
/usr/local/lib/python3.10/dist-packages/matplotlib/backends/backend_agg.py in _prepare_font(self, font_prop)
    268         font.clear()
    269         size = font_prop.get_size_in_points()
--> 270         font.set_size(size, self.dpi)
    271         return font
    272 

RuntimeError: In set_size: Could not set the fontsize (invalid ppem value; error code 0x97)
<Figure size 16.256x12.192 with 2 Axes>

Does someone know how to fix this? It seems to be an issue with matplotlib and the measurements of my Figure.
<p>I have some complex code that I need to run in Google Colab (students will use this for a test). I reproduced my error in a smaller piece of code, i try to create a simple heatmap. I already set the font to the Colab default (monospace) and sepcified a font size. Also DPI was adjusted to avoid the error.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import csv
import time

# Clear the font cache and set font settings
import matplotlib as mpl
mpl.font_manager._load_fontmanager()
plt.rcParams['font.family'] = 'monospace'
plt.rcParams['font.size'] = 10

# Start time
t_start = time.time()

# Example data for testing
np.random.seed(0)
L_dataset = np.random.rand(10, 10) * 100 # Random data between 0 and 100

# Transform list to array
A_dataset = np.array(L_dataset, dtype=np.float32)

try:
# Set the figure size in inches and specify DPI
plt.figure(figsize=(11, 8), dpi=100)

# Create heat map
fig, ax = plt.subplots()
cax = ax.matshow(A_dataset, cmap='OrRd', vmin=0, vmax=100)

# Add colorbar
fig.colorbar(cax)

# Set tick marks for grid lines
ax.set_xticks(np.arange(-.5, len(A_dataset[0]), 1), minor=True)
ax.set_yticks(np.arange(-.5, len(A_dataset), 1), minor=True)

# Gridlines based on minor ticks
ax.grid(which='minor', color='white', linestyle='-', linewidth=2)

# Loop to annotate each cell with its value
for i in range(A_dataset.shape[0]):
for j in range(A_dataset.shape[1]):
ax.text(j, i, '{:0.2f}'.format(A_dataset[i, j]), ha='center', va='center', color='white')

plt.grid(which='both', color='white', linestyle='-', linewidth=0) # Optional: add grid lines
plt.title('Heatmap of A_dataset')

# Save the plot as a PNG image in the "dir" directory
filename = 'HeatMap.png'
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.clf() # clear the figure to start with a new blank figure

except RuntimeError as e:
print(f"RuntimeError: {e}")

# End and print time
print('Time elapsed for running module "N_VA_HeatMap": {:.3f} sec.'.format(time.time() - t_start))
</code></pre>
<p>The error I get is:</p>
<pre><code>RuntimeError: In set_size: Could not set the fontsize (invalid ppem value; error code 0x97)
Time elapsed for running module "N_VA_HeatMap": 1.611 sec.
<Figure size 1100x800 with 0 Axes>
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/IPython/core/formatters.py in __call__(self, obj)
339 pass
340 else:
--> 341 return printer(obj)
342 # Finally look for special method names
343 method = get_real_method(obj, self.print_method)

19 frames
/usr/local/lib/python3.10/dist-packages/matplotlib/backends/backend_agg.py in _prepare_font(self, font_prop)
268 font.clear()
269 size = font_prop.get_size_in_points()
--> 270 font.set_size(size, self.dpi)
271 return font
272

RuntimeError: In set_size: Could not set the fontsize (invalid ppem value; error code 0x97)
<Figure size 16.256x12.192 with 2 Axes>
</code></pre>
<p>Does someone know how to fix this? It seems to be an issue with matplotlib and the measurements of my Figure.</p>
 

Online statistics

Members online
0
Guests online
4
Total visitors
4
Top