Skip to content

Instantly share code, notes, and snippets.

@ahmethakanbesel
Created June 21, 2023 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmethakanbesel/b7978fe4ca4b1813bae3002ad2015230 to your computer and use it in GitHub Desktop.
Save ahmethakanbesel/b7978fe4ca4b1813bae3002ad2015230 to your computer and use it in GitHub Desktop.
Visualize exam grades by creating histograms with Plotly.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"import plotly.graph_objects as go\n",
"import numpy as np\n",
"\n",
"with open('grades.txt', 'r') as f:\n",
" exam_grades = f.readlines()\n",
"\n",
"# convert the strings into integers and assign them to a new list\n",
"grades = [int(grade) for grade in exam_grades]\n",
"\n",
"tick_vals = ['[0, 10)', '[10, 20)', '[20, 30)', '[30, 40)', '[40, 50)', '[50, 60)', '[60, 70)', '[70, 80)', '[80, 90)',\n",
" '[90, 100)', '[100, 110)']\n",
"\n",
"for i in range(len(tick_vals)):\n",
" tick_vals[i] = ' ' + tick_vals[i]\n",
"\n",
"# Initialize a dictionary to hold the counts for each bin\n",
"histogram = [0] * 11\n",
"bins = []\n",
"# Count the scores in each bin\n",
"for s in grades:\n",
" for b in range(0, 12):\n",
" bin = b * 10\n",
" bins.append(bin + 1)\n",
" if bin <= s < bin + 10:\n",
" histogram[b] += 1\n",
"\n",
"# Create a trace for the bar plot\n",
"trace = go.Bar(\n",
" x=bins, # the bin edges are the x-values, but we don't want to include the rightmost edge\n",
" y=histogram,\n",
" text=['{} ({:.1f}%)'.format(count, count / sum(histogram) * 100) for count in histogram],\n",
" # show count and percentage\n",
" textposition='auto',\n",
" hoverinfo='none',\n",
" width=10, # set the width of the bars\n",
" marker={'color': bins,\n",
" 'colorscale': 'rdylgn'}\n",
")\n",
"\n",
"# Calculate the statistics to be displayed in the legend\n",
"min_score = min(grades)\n",
"max_score = max(grades)\n",
"mean = sum(grades) / len(grades)\n",
"median = np.median(grades)\n",
"mode = max(histogram)\n",
"\n",
"# Create the layout for the plot\n",
"layout = go.Layout(\n",
" xaxis=dict(\n",
" showticklabels=True,\n",
" tick0=0,\n",
" nticks=10,\n",
" dtick=10,\n",
" tickangle=0,\n",
" showgrid=False,\n",
" tickmode='array',\n",
" tickvals=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110],\n",
" ticktext=tick_vals\n",
" ),\n",
" yaxis=dict(title='Count'), # set the y-axis title\n",
" bargap=0, # set the gap between the bars\n",
")\n",
"\n",
"# Create a table trace for the statistics\n",
"table_trace = go.Table(\n",
" header=dict(values=['Statistic', 'Value']), # set the column names\n",
" cells=dict(values=[['Minimum', 'Maximum', 'Mean', 'Median', 'Mode'], [min_score, max_score, mean, median, mode]]),\n",
")\n",
"\n",
"print(f\"Min: {min_score:.2f} Max: {max_score:.2f} Mean: {mean:.2f} Median: {median:.2f}\")\n",
"\n",
"# Create the figure and plot\n",
"fig = go.Figure(data=[trace], layout=layout)\n",
"fig.update_layout(\n",
" title_text=\"Exam Grades\",\n",
" font_family=\"Arial\",\n",
" font_size=18,\n",
" title_font_family=\"Arial\",\n",
" title_font_color=\"black\",\n",
" legend_title_font_color=\"black\"\n",
")\n",
"fig.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
import plotly.graph_objects as go
import numpy as np
with open('grades.txt', 'r') as f:
exam_grades = f.readlines()
# convert the strings into integers and assign them to a new list
grades = [int(grade) for grade in exam_grades]
tick_vals = ['[0, 10)', '[10, 20)', '[20, 30)', '[30, 40)', '[40, 50)', '[50, 60)', '[60, 70)', '[70, 80)', '[80, 90)',
'[90, 100)', '[100, 110)']
for i in range(len(tick_vals)):
tick_vals[i] = ' ' + tick_vals[i]
# Initialize a dictionary to hold the counts for each bin
histogram = [0] * 11
bins = []
# Count the scores in each bin
for s in grades:
for b in range(0, 12):
bin = b * 10
bins.append(bin + 1)
if bin <= s < bin + 10:
histogram[b] += 1
# Create a trace for the bar plot
trace = go.Bar(
x=bins, # the bin edges are the x-values, but we don't want to include the rightmost edge
y=histogram,
text=['{} ({:.1f}%)'.format(count, count / sum(histogram) * 100) for count in histogram],
# show count and percentage
textposition='auto',
hoverinfo='none',
width=10, # set the width of the bars
marker={'color': bins,
'colorscale': 'rdylgn'}
)
# Calculate the statistics to be displayed in the legend
min_score = min(grades)
max_score = max(grades)
mean = sum(grades) / len(grades)
median = np.median(grades)
mode = max(histogram)
# Create the layout for the plot
layout = go.Layout(
xaxis=dict(
showticklabels=True,
tick0=0,
nticks=10,
dtick=10,
tickangle=0,
showgrid=False,
tickmode='array',
tickvals=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110],
ticktext=tick_vals
),
yaxis=dict(title='Count'), # set the y-axis title
bargap=0, # set the gap between the bars
)
# Create a table trace for the statistics
table_trace = go.Table(
header=dict(values=['Statistic', 'Value']), # set the column names
cells=dict(values=[['Minimum', 'Maximum', 'Mean', 'Median', 'Mode'], [min_score, max_score, mean, median, mode]]),
)
print(f"Min: {min_score:.2f} Max: {max_score:.2f} Mean: {mean:.2f} Median: {median:.2f}")
# Create the figure and plot
fig = go.Figure(data=[trace], layout=layout)
fig.update_layout(
title_text="Exam Grades",
font_family="Arial",
font_size=18,
title_font_family="Arial",
title_font_color="black",
legend_title_font_color="black"
)
fig.show()
95
90
85
85
77
65
65
63
60
60
58
55
55
52
50
50
40
40
40
40
35
35
32
32
32
30
30
30
30
27
27
27
27
25
25
25
25
25
25
25
25
25
22
20
20
20
20
20
15
15
15
12
10
10
10
10
10
10
10
10
10
5
5
5
5
5
5
1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment