The code reads data from an Excel file, generates bar charts for each subject column (excluding the first "Slab" column), and saves them as PNG images with informative titles and labels.
The Excel file can have dynamic sets of values for each Subject in the following format:
Slab,Eng,Math,Sci,Social,II Hindi,II French,II Telugu,III Hindi,III French,III Telugu
90 to < 100,4,9,10,9,2,1,1,1,1,2
80 to < 90 ,10,7,6,2,6,0,1,0,1,2
70 to < 80 ,2,2,3,2,2,0,2,1,0,3
60 to < 70 ,2,3,2,3,1,0,1,0,1,7
0 to <60,12,9,9,15,5,2,5,3,0,7
Code Explanation by Gemini -
Imports:
pandas as pd: Imports the pandas library for data manipulation (used to read the Excel file).
matplotlib.pyplot as plt: Imports the matplotlib library for creating plots.
from matplotlib.ticker import MaxNLocator: Imports the MaxNLocator class from matplotlib to ensure only integer values are shown on the y-axis.
Loading the Data:
excel_file: Defines the path to your Excel file (needs to be replaced with your actual path).
sheet_name: Defines the sheet name in the Excel file (optional, defaults to "Sheet1").
df = pd.read_excel(excel_file, sheet_name=sheet_name): Reads the Excel file into a pandas DataFrame named df.
Debugging:
print("Column names:", df.columns): Prints the column names of the DataFrame to verify data is loaded correctly.
Iterating over Subjects:
for subject in df.columns[1:]:: Loops through each column in the DataFrame except the first one (assuming the first column is "Slab").
print(f"Generating chart for: {subject}"): Prints a message indicating which subject's chart is being generated (helpful for debugging).
Generating Chart:
plt.figure(figsize=(10, 6)): Creates a new figure window for the chart with a specific size (10x6 inches).
try...except block: This block handles potential errors during chart creation.
bars = plt.bar(df['Slab'], df[subject], color='skyblue'): Creates a bar chart with "Slab" on the x-axis, the current "subject" column on the y-axis, and a sky blue color.
print(f"Error plotting {subject}: {e}"): If an error occurs, it prints an error message with the subject name and the error details.
plt.xlabel...plt.title...: These lines set labels and title for the chart, including subject name for clarity.
plt.gca().yaxis.set_major_locator(MaxNLocator(integer=True)): Ensures the y-axis only shows integer values (number of students).
for bar in bars...: Iterates over each bar in the chart and adds the student count value as text on top of the bar.
try...except block: This block handles potential errors while saving the chart.
plt.savefig(rf'C:\scores{subject}.png'): Saves the chart as a PNG image with the subject name in the "scores" folder (replace with your desired path).
print(f"Error saving {subject} chart: {e}"): If an error occurs during saving, it prints an error message with the subject name and the error details.
plt.close(): Closes the current figure window to avoid overlapping plots.