Creating a graph in excel

Hi Simon,

You could try the code below and that will save the image in the excel file and give you a separate image file also.

import pandas as pd
import matplotlib.pyplot as plt
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.drawing.image import Image

# Read the data from Excel file
df = pd.read_excel("yield vs CWP_original.xlsx", skiprows=[1], usecols=[1, 4])

x = df["CWP"]
y = df["YIELD"]

# Create the scatter plot
plt.scatter(x, y)
plt.xlabel('CWP')
plt.ylabel('YIELD')
plt.title('Yield vs CWP')

# Save the plot as an image
plot_image_path = "scatter_plot.png"
plt.savefig(plot_image_path)

# Load the Excel file using openpyxl
wb = openpyxl.load_workbook("yield vs CWP_original.xlsx")
sheet = wb.active

# Insert the image in the Excel sheet
img = Image(plot_image_path)
sheet.add_image(img, "E2")  # You can change the cell reference (E2) as per your preference

# Save the modified Excel file
wb.save("yield vs CWP_original.xlsx")

# Close the plot
plt.close()