Paste the matplotlib figure on excel

background purpose

I'm tired of being able to fill up a lot of image files, so I want to paste them in one Excel file.

policy

Save the figure to a file in image format and paste the image with insert_image of xlsxwriter It seems useless to write it out once, but I think this is the easiest

Sample code and result image

import matplotlib.pyplot as plt
import numpy as np

#Create sample figure
plt.close(1)  #It doesn't have to be, but it's an initial feeling
fig, ax = plt.subplots(1, 1, figsize=(6,3))
ax.barh(y=range(10),width=range(10))
plt.tight_layout()

#Save image
image_file_path = 'tmp.png'
fig.savefig(image_file_path)

#Open a new workbook, create a sheet
import xlsxwriter
workbook = xlsxwriter.Workbook('tmp.xlsx')
worksheet = workbook.add_worksheet()

#Paste the image in the cell
worksheet.insert_image('A1', image_file_path)
worksheet.insert_image('K1', image_file_path, {'x_scale': 0.7, 'y_scale': 0.7})
worksheet.insert_image(19, 0, image_file_path)
worksheet.insert_image(19, 10, image_file_path)

#Zoom adjustment
worksheet.set_zoom(50)

#Close the Excel workbook and finish
workbook.close()

image.png

reference

Official documentation for xlsxwriter. It's fairly solid. search is convenient. https://xlsxwriter.readthedocs.io/worksheet.html#insert_image

Recommended Posts

Paste the matplotlib figure on excel
Paste the link on linux
Notes on using matplotlib on the server
Match the colorbar to the figure with matplotlib
Add information to the bottom of the figure with Matplotlib
Paste the image into an excel file using Python's openpyxl
Manipulate the clipboard in Python and paste the table into Excel
Code to send an email based on the Excel email list
Notes on coloring by value in the matplotlib scatter plot
Graph Excel data with matplotlib (1)
Use matplotlib on Ubuntu 12 & Python
The road to download Matplotlib
Set matplotlib font on ubuntu
Graph Excel data with matplotlib (2)
Watch the video on Fedora31
Change the style of matplotlib
View matplotlib plots on Tensorboard