Skip to main content

Matplotlib Figure Variable Matches Saved Png File

Check if a Matplotlib figure variable matches a saved png file.

Location of the snippet: python/matplotlib/matplotlib_figure_variable_matches_saved_png_file

This snippet is used to compare a student's Matplotlib figure with a reference PNG file. The default figure variable name is fig, and the default location for the PNG file is /root/.cache/.local/.trash/.

If left blank, the default values will be used. If the figure variable name is not fig, it must be specified. If the location is not /root/.cache/.local/.trash/, it must be specified.

Device Type
Jupyter

Variables:

Variable NameVariable DescriptionTypeRequired?Default
student_figure_variable_nameName of the student's Matplotlib figure variable.strNo
png_file_nameName of the png file to compare against.strYes
locationDirectory where the png file is located.strNo

Examples:

1. Basic Line Plot Comparison (Default Figure Name and Location)

This example checks if a student's generated line plot (saved in a variable named fig) matches a reference PNG.

Scenario: Students need to create a simple line plot showing the values [1, 2, 3, 4, 5] on the y-axis against [0, 1, 2, 3, 4] on the x-axis, with a title and labels.

Task: Generate a Matplotlib line plot where y = [1, 2, 3, 4, 5] and x = [0, 1, 2, 3, 4]. Title it "Simple Line Plot", with x-axis "X-axis Label" and y-axis "Y-axis Label". Store the figure object in a variable named fig.

Placeholder:

fig, ax = plt.subplots(...)
# Your code to create the plot

Solution:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = np.array([1, 2, 3, 4, 5])

fig, ax = plt.subplots(figsize=(6,4)) # Create a figure and axes
ax.plot(x, y)
ax.set_title("Simple Line Plot")
ax.set_xlabel("X-axis Label")
ax.set_ylabel("Y-axis Label")

Serialization:

import matplotlib.pyplot as plt
import numpy as np
import os

# Create the reference plot
x_ref = np.arange(5)
y_ref = np.array([1, 2, 3, 4, 5])

ref_fig, ref_ax = plt.subplots(figsize=(6,4))
ref_ax.plot(x_ref, y_ref)
ref_ax.set_title("Simple Line Plot")
ref_ax.set_xlabel("X-axis Label")
ref_ax.set_ylabel("Y-axis Label")

# Define the default location
default_location = "/root/.cache/.local/.trash/"
os.makedirs(default_location, exist_ok=True) # Ensure the directory exists

# Define the reference file path
reference_file_name = "expected_line_plot_ex1.png"
reference_file_path = os.path.join(default_location, reference_file_name)

# Save the figure to PNG
ref_fig.savefig(reference_file_path)

print(f"Reference PNG saved to: {reference_file_path}")

Snippet for the assertion:

Variable NameValue
png_file_nameexpected_line_plot_ex1.png

2. Bar Chart Comparison with Custom Figure Name and Location

This example checks a bar chart, where the student's figure variable has a specific name and the reference PNG is in a custom location.

Scenario: Students are asked to create a bar chart of product sales for 'Apple', 'Banana', and 'Orange' with sales figures 100, 150, 80 respectively. They should store the figure object in a variable named sales_chart_fig.

Task: Generate a Matplotlib bar chart showing sales per product. Products: ['Apple', 'Banana', 'Orange'], Sales: [100, 150, 80]. Title it "Product Sales", with x-axis "Product" and y-axis "Sales". Store the figure object in sales_chart_fig.

Placeholder:

sales_chart_fig, ax = plt.subplots(...)
# Your code to create the bar chart

Solution:

import matplotlib.pyplot as plt

products = ['Apple', 'Banana', 'Orange']
sales = [100, 150, 80]

sales_chart_fig, ax = plt.subplots(figsize=(7,5))
ax.bar(products, sales)
ax.set_title("Product Sales")
ax.set_xlabel("Product")
ax.set_ylabel("Sales")
plt.close(sales_chart_fig)

Serialization:

import matplotlib.pyplot as plt
import os

# Create the reference bar chart
products_ref = ['Apple', 'Banana', 'Orange']
sales_ref = [100, 150, 80]

ref_sales_chart_fig, ref_ax = plt.subplots(figsize=(7,5))
ref_ax.bar(products_ref, sales_ref)
ref_ax.set_title("Product Sales")
ref_ax.set_xlabel("Product")
ref_ax.set_ylabel("Sales")

# Define a custom location
custom_location = "/test_resources/plots/"
os.makedirs(custom_location, exist_ok=True) # Ensure the directory exists

# Define the reference file path
reference_file_name = "expected_sales_bar_chart_ex2.png"
reference_file_path = os.path.join(custom_location, reference_file_name)

# Save the figure to PNG
ref_sales_chart_fig.savefig(reference_file_path)
plt.close(ref_sales_chart_fig)

print(f"Reference PNG saved to: {reference_file_path}")
Variable NameValue
student_figure_variable_namesales_chart_fig
png_file_nameexpected_sales_bar_chart_ex2.png
location/test_resources/plots/