Python Forum

Full Version: [solved] Save a matplotlib figure into hdf5 file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

I've tried several methods to save directly a figure from Matplotlib into a hdf5 file, but Hdfview cannot open the file ("error opening file"): does somebody know the good way?

The last trial I did where "fig" is the object coming from Matplotlib:

FigArray = np.array(canvas.renderer.buffer_rgba(), dtype=np.uint8)
h5 = h5py.File('picture.h5', 'w')
ImageGroup = h5.require_group('Pictures')
ImageDataset = ImageGroup .create_dataset(name='picture', data=FigArray)
Thanks for your help
After digging into internet, and some trials, I guess I'm closed to what I'm looking for Wink (from a Matplotlib example)

Some options remain unclear and I need to go deeper, but it works

Feedbacks will be appreciated

from cycler import cycler
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvas
import os, h5py

PATH = str(os.getcwd())

# Define a list of markevery cases and color cases to plot
cases = [None,
         (30, 8),
         [16, 24, 30],
         [0, -1],
         slice(100, 200, 3),
         (0.0, 0.1),
         (0.45, 0.1)]

colors = ['#1f77b4',

# Configure rcParams axes.prop_cycle to simultaneously cycle cases and colors.
mpl.rcParams['axes.prop_cycle'] = cycler(markevery=cases, color=colors)

# Create data points and offsets
x = np.linspace(0, 2 * np.pi)
offsets = np.linspace(0, 2 * np.pi, 11, endpoint=False)
yy = np.transpose([np.sin(x + phi) for phi in offsets])

# Set the plot curve with markers and a title
fig = plt.figure(figsize=(16, 16))
ax = fig.add_axes([0.1, 0.1, 0.6, 0.75])

for i in range(len(cases)):
    ax.plot(yy[:, i], marker='o', label=str(cases[i]))
    ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)

plt.title('Support for axes.prop_cycle cycler with markevery')

## From Matplotlib to NumpyArray        
canvas = FigureCanvas(fig)
FigArray = np.array(canvas.renderer.buffer_rgba())

## To hdf5
PATH = str(os.getcwd())
h5 = h5py.File(PATH + '/test_picture.h5', 'w')
ImageDataset = h5.create_dataset(name="Example_picture", data=FigArray, dtype='uint8', chunks=True, compression='gzip', compression_opts=9)
ImageDataset.attrs["CLASS"] = np.string_("IMAGE")
ImageDataset.attrs["IMAGE_VERSION"] = np.string_("1.2")
ImageDataset.attrs["IMAGE_SUBCLASS"] = np.string_("IMAGE_TRUECOLOR")
ImageDataset.attrs["INTERLACE_MODE"] = np.string_("INTERLACE_MODE")
ImageDataset.attrs["IMAGE_MINMAXRANGE"] = np.uint8(0.255)