Skip to content

Instantly share code, notes, and snippets.

@mvark
Last active September 17, 2024 15:38
Show Gist options
  • Save mvark/33b3e4d27c4fcce5ff99eb5b4ef3f0ad to your computer and use it in GitHub Desktop.
Save mvark/33b3e4d27c4fcce5ff99eb5b4ef3f0ad to your computer and use it in GitHub Desktop.
Python script to generate charts showing class performance in different subjects by slabs after picking scores for each Subject from an Excel file
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
# Load the Excel file into a DataFrame
excel_file = r'C:\scores\scores.xlsx' # Replace with your Excel file path
sheet_name = 'Sheet1' # Replace with your sheet name if necessary
df = pd.read_excel(excel_file, sheet_name=sheet_name)
# Debug: Print column names
print("Column names:", df.columns)
# Iterate over each subject column (excluding the 'Slab' column)
for subject in df.columns[1:]:
# Debug: Print current subject
print(f"Generating chart for: {subject}")
# Step 3: Generate the column chart
plt.figure(figsize=(10, 6))
# Plot the column chart
try:
bars = plt.bar(df['Slab'], df[subject], color='skyblue') # Assign the result to 'bars'
except Exception as e:
print(f"Error plotting {subject}: {e}")
continue
# Add labels and title
plt.xlabel('Marks', fontweight='bold')
plt.ylabel('Number of Students', fontweight='bold')
plt.title(f'Marks Distribution for {subject}')
# Ensure y-axis shows only integer values
plt.gca().yaxis.set_major_locator(MaxNLocator(integer=True))
# Show count within the columns
for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2, yval, int(yval), va='bottom', ha='center')
# Save the chart as an image file
try:
plt.savefig(rf'C:\scores\{subject}.png') # Replace with your desired file path and name
except Exception as e:
print(f"Error saving {subject} chart: {e}")
continue
# Close the plot to avoid overlap
plt.close()

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment