![]() |
[solved] Save a matplotlib figure into hdf5 file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: [solved] Save a matplotlib figure into hdf5 file (/thread-33897.html) |
[solved] Save a matplotlib figure into hdf5 file - paul18fr - Jun-08-2021 Hi 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 RE: [solved] Save a matplotlib figure into hdf5 file - paul18fr - Jun-08-2021 After digging into internet, and some trials, I guess I'm closed to what I'm looking for ![]() 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, 8, (30, 8), [16, 24, 30], [0, -1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', '#1a55FF'] # 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') plt.show() ## From Matplotlib to NumpyArray canvas = FigureCanvas(fig) canvas.draw() 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) h5.close() |