DESN2003
  • Home
  • Assessment
  • Writing Samples

On this page

  • Week 10 Hands-On: Data Visualization
    • 1. Inspect The Data First
    • 2. Core Quantitative Visualizations
    • 3. Advanced / Presentation-Ready Visualizations
    • 4. Qualitative Visualizations
    • 5. Student Sandbox
    • 6. If Students Want To Use Their Own Data
    • 7. Beyond Colab: Plotly, Flourish, and D3.js

Open In Colab

Week 10 Hands-On: Data Visualization

This notebook is designed for DESN2003 Week 10. It starts with the core beginner charts from the lecture, then extends into a few richer presentation-ready examples.

By the end, students should be able to: - inspect a small dataset before plotting it - compare groups with box plots, histograms, bar charts, and heatmaps - read relationships with scatter plots and matrix views - experiment with treemaps, Sankey diagrams, and choropleth-style maps - create quick qualitative visuals from transcript text - understand when a tool like Plotly or D3.js becomes useful

The sample data is baked into the notebook. The notebook also writes out survey_data.csv and transcripts.json in the runtime so students can inspect or reuse them.

from io import StringIO
from pathlib import Path
import json

from IPython.display import display
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

try:
    from wordcloud import STOPWORDS, WordCloud
except ImportError:
    import subprocess
    import sys

    subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', 'wordcloud'])
    from wordcloud import STOPWORDS, WordCloud

try:
    import plotly.graph_objects as go
except ImportError:
    import subprocess
    import sys

    subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', 'plotly'])
    import plotly.graph_objects as go

sns.set_theme(style='whitegrid', context='talk')
plt.rcParams['figure.figsize'] = (8, 5)
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.right'] = False
pd.set_option('display.max_colwidth', 140)
survey_csv = """ParticipantID,Group,Region,Score,Satisfaction,Recommend,Comment
1,GenAI,Africa,88,5,Yes,The AI tutor made studying much easier.
2,Traditional,Africa,65,3,No,Studying without AI was a bit challenging.
3,GenAI,Asia,79,4,Yes,The AI answered my questions quickly.
4,GenAI,Asia,78,4,Yes,The AI provided clear explanations.
5,Traditional,Asia,70,4,Yes,Studying on my own worked fine for me.
6,Traditional,Asia,60,3,No,"It was okay, but I think AI might have helped."
7,GenAI,Europe,82,4,Yes,Having an AI assistant was extremely helpful.
8,GenAI,Europe,85,5,Yes,Using the AI tool saved me a lot of time.
9,Traditional,Europe,68,3,No,"I did all right, but it took a lot of time."
10,Traditional,Europe,58,2,No,Learning without AI was a good experience.
11,GenAI,North America,92,5,Yes,ChatGPT was a great help in my studies.
12,GenAI,North America,81,4,Yes,Using the AI support improved my understanding.
13,GenAI,North America,66,2,No,"The AI's answers were often confusing."
14,GenAI,North America,74,3,No,The AI was somewhat helpful but not perfect.
15,Traditional,North America,75,4,Yes,I did well without using any AI.
16,Traditional,North America,77,4,Yes,I felt confident even without an AI helper.
17,Traditional,South America,50,1,No,It was really hard without any AI assistance.
18,Traditional,South America,72,3,No,I struggled a lot to learn by myself.
19,GenAI,South America,90,5,Yes,I found the AI help very useful for learning.
20,Traditional,South America,83,5,Yes,I managed to learn everything without AI.
"""

transcripts = [
    {
        'id': 1,
        'group': 'GenAI',
        'text': (
            'I tried using ChatGPT to help me study for my exams. At first I was not sure, '
            'but it turned out to be extremely helpful. Whenever I had a question, the AI '
            'provided an explanation right away. It felt like having a tutor available 24/7. '
            'It saved me so much time because I did not have to search for answers on my own. '
            'I am definitely going to keep using such tools for learning.'
        ),
    },
    {
        'id': 2,
        'group': 'GenAI',
        'text': (
            'I used an AI chatbot for help in my course, but it was not as great as I expected. '
            'Sometimes it gave me answers that were confusing or even wrong. I ended up spending '
            'extra time double-checking the information it provided. It was frustrating because I '
            'was never sure if I could trust the answers. In the end, I felt like it did not '
            'improve my learning much.'
        ),
    },
    {
        'id': 3,
        'group': 'Traditional',
        'text': (
            'I decided not to use any AI or online tutors while studying. I wanted to do '
            'everything myself using textbooks and class notes. It was a real challenge and '
            'took me a lot longer to get through the material. There were times I got stuck '
            'on a concept and had no one to ask for help. I think I learned the material '
            'eventually, but I was pretty stressed. After seeing others use AI tools, I am '
            'considering trying it in the future.'
        ),
    },
]

region_to_country = {
    'Africa': ('Nigeria', 'NGA'),
    'Asia': ('India', 'IND'),
    'Europe': ('Germany', 'DEU'),
    'North America': ('United States', 'USA'),
    'South America': ('Brazil', 'BRA'),
}

Path('survey_data.csv').write_text(survey_csv, encoding='utf-8')
Path('transcripts.json').write_text(json.dumps(transcripts, indent=2), encoding='utf-8')

survey_df = pd.read_csv(StringIO(survey_csv))
survey_df['CommentLength'] = survey_df['Comment'].str.split().str.len()
survey_df['PositiveRecommend'] = survey_df['Recommend'].eq('Yes').astype(int)
survey_df['SatisfactionBand'] = pd.cut(
    survey_df['Satisfaction'],
    bins=[0, 2, 3, 5],
    labels=['Low (1-2)', 'Medium (3)', 'High (4-5)'],
    include_lowest=True,
)
survey_df['Country'] = survey_df['Region'].map(lambda value: region_to_country[value][0])
survey_df['ISO3'] = survey_df['Region'].map(lambda value: region_to_country[value][1])
transcript_df = pd.DataFrame(transcripts)

survey_df.head()
ParticipantID Group Region Score Satisfaction Recommend Comment CommentLength PositiveRecommend SatisfactionBand Country ISO3
0 1 GenAI Africa 88 5 Yes The AI tutor made studying much easier. 7 1 High (4-5) Nigeria NGA
1 2 Traditional Africa 65 3 No Studying without AI was a bit challenging. 7 0 Medium (3) Nigeria NGA
2 3 GenAI Asia 79 4 Yes The AI answered my questions quickly. 6 1 High (4-5) India IND
3 4 GenAI Asia 78 4 Yes The AI provided clear explanations. 5 1 High (4-5) India IND
4 5 Traditional Asia 70 4 Yes Studying on my own worked fine for me. 8 1 High (4-5) India IND

1. Inspect The Data First

Before plotting anything, make sure students can answer basic questions: - What columns do we have? - Which columns are numeric, and which are categories? - How many students are in each group? - What does the text feedback actually sound like?

print(f'Rows, columns: {survey_df.shape}')
print()
print('Column types:')
survey_df.info()
print()
print('Numeric summary:')
display(survey_df.select_dtypes(include='number').describe().round(2))
print()
print('Group summary:')
display(survey_df.groupby('Group')[['Score', 'Satisfaction', 'CommentLength']].mean().round(2))
print()
print('Recommend by group:')
display(pd.crosstab(survey_df['Group'], survey_df['Recommend']))
Rows, columns: (20, 12)

Column types:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20 entries, 0 to 19
Data columns (total 12 columns):
 #   Column             Non-Null Count  Dtype   
---  ------             --------------  -----   
 0   ParticipantID      20 non-null     int64   
 1   Group              20 non-null     object  
 2   Region             20 non-null     object  
 3   Score              20 non-null     int64   
 4   Satisfaction       20 non-null     int64   
 5   Recommend          20 non-null     object  
 6   Comment            20 non-null     object  
 7   CommentLength      20 non-null     int64   
 8   PositiveRecommend  20 non-null     int64   
 9   SatisfactionBand   20 non-null     category
 10  Country            20 non-null     object  
 11  ISO3               20 non-null     object  
dtypes: category(1), int64(5), object(6)
memory usage: 2.0+ KB

Numeric summary:

Group summary:

Recommend by group:
ParticipantID Score Satisfaction CommentLength PositiveRecommend
count 20.00 20.00 20.00 20.00 20.0
mean 10.50 74.65 3.65 7.70 0.6
std 5.92 11.15 1.14 1.45 0.5
min 1.00 50.00 1.00 5.00 0.0
25% 5.75 67.50 3.00 7.00 0.0
50% 10.50 76.00 4.00 7.50 1.0
75% 15.25 82.25 4.25 8.00 1.0
max 20.00 92.00 5.00 11.00 1.0
Score Satisfaction CommentLength
Group
GenAI 81.5 4.1 7.3
Traditional 67.8 3.2 8.1
Recommend No Yes
Group
GenAI 2 8
Traditional 6 4

2. Core Quantitative Visualizations

These examples match the core chart families from the lecture and are deliberately easy to edit.

palette = {'GenAI': '#2A9D8F', 'Traditional': '#E76F51'}

plt.figure(figsize=(7, 5))
ax = sns.boxplot(
    data=survey_df,
    x='Group',
    y='Score',
    hue='Group',
    dodge=False,
    palette=palette,
)
if ax.legend_:
    ax.legend_.remove()
plt.title('Test Score Distribution by Group')
plt.xlabel('Learning Method')
plt.ylabel('Test Score')
plt.show()

plt.figure(figsize=(8, 5))
sns.histplot(
    data=survey_df,
    x='Score',
    hue='Group',
    bins=8,
    multiple='layer',
    alpha=0.45,
    palette=palette,
)
plt.title('Score Distribution')
plt.xlabel('Test Score')
plt.ylabel('Number of Students')
plt.show()

recommend_palette = {'Yes': '#2A9D8F', 'No': '#E76F51'}

plt.figure(figsize=(7, 5))
sns.countplot(data=survey_df, x='Group', hue='Recommend', palette=recommend_palette)
plt.title('Would Students Recommend The Method?')
plt.xlabel('Learning Method')
plt.ylabel('Number of Students')
plt.legend(title='Recommend')
plt.show()

region_scores = (
    survey_df.groupby(['Region', 'Group'], as_index=False, observed=False)['Score']
    .mean()
    .sort_values(['Region', 'Group'])
)

plt.figure(figsize=(11, 5))
sns.barplot(data=region_scores, x='Region', y='Score', hue='Group', palette=palette)
plt.title('Average Score By Region')
plt.xlabel('Region')
plt.ylabel('Average Score')
plt.xticks(rotation=20, ha='right')
plt.legend(title='Group')
plt.show()

numeric_cols = ['Score', 'Satisfaction', 'CommentLength', 'PositiveRecommend']
corr = survey_df[numeric_cols].corr()
outcome_matrix = pd.crosstab(survey_df['Group'], survey_df['Recommend'])

fig, axes = plt.subplots(1, 2, figsize=(15, 5))

sns.heatmap(corr, annot=True, cmap='YlGnBu', vmin=-1, vmax=1, ax=axes[0])
axes[0].set_title('Correlation Heatmap')

sns.heatmap(outcome_matrix, annot=True, fmt='d', cmap='mako', ax=axes[1])
axes[1].set_title('Outcome Matrix: Group vs Recommend')
axes[1].set_xlabel('Recommend')
axes[1].set_ylabel('Group')

plt.tight_layout()
plt.show()

plt.figure(figsize=(7, 5))
sns.scatterplot(
    data=survey_df,
    x='Score',
    y='Satisfaction',
    hue='Group',
    s=140,
    palette=palette,
)
plt.title('Score vs Satisfaction')
plt.ylim(0.8, 5.2)
plt.show()

3. Advanced / Presentation-Ready Visualizations

These next examples are not required for a beginner workflow, but they are useful when a static bar chart is not the clearest way to tell the story.

region_group_counts = (
    survey_df.groupby(['Region', 'Group'], as_index=False, observed=False)
    .agg(Count=('ParticipantID', 'count'), AverageScore=('Score', 'mean'))
    .sort_values(['Region', 'Group'])
)

labels = []
parents = []
values = []
colors = []
text = []

for region, region_df in region_group_counts.groupby('Region', observed=False):
    labels.append(region)
    parents.append('')
    values.append(int(region_df['Count'].sum()))
    colors.append(float(region_df['AverageScore'].mean()))
    text.append(f"{int(region_df['Count'].sum())} students")

    for row in region_df.itertuples(index=False):
        labels.append(f"{row.Region} | {row.Group}")
        parents.append(row.Region)
        values.append(int(row.Count))
        colors.append(float(row.AverageScore))
        text.append(f"{row.Count} students<br>Avg score {row.AverageScore:.1f}")

fig = go.Figure(
    go.Treemap(
        labels=labels,
        parents=parents,
        values=values,
        text=text,
        textinfo='label+text',
        marker=dict(colors=colors, colorscale='Tealrose', showscale=True),
        branchvalues='total',
        hovertemplate='%{label}<br>%{text}<extra></extra>',
    )
)
fig.update_layout(title='Treemap: Region and Group Counts', margin=dict(t=60, l=20, r=20, b=20))
fig.show()

Choropleth Note

Our teaching dataset stores regions, not actual country or district codes. To demonstrate the mechanics of a choropleth, this example maps each region to a representative country code. For real work, use the real geographic unit from your study.

region_map = (
    survey_df.groupby(['Region', 'Country', 'ISO3'], as_index=False, observed=False)
    .agg(Participants=('ParticipantID', 'count'), AverageScore=('Score', 'mean'))
    .sort_values('Participants', ascending=False)
)

fig = go.Figure(
    go.Choropleth(
        locations=region_map['ISO3'],
        z=region_map['AverageScore'],
        text=region_map['Country'],
        customdata=region_map[['Region', 'Participants']],
        colorscale='Viridis',
        colorbar_title='Avg Score',
        marker_line_color='white',
        hovertemplate=(
            '%{text}<br>'
            'Region: %{customdata[0]}<br>'
            'Participants: %{customdata[1]}<br>'
            'Average score: %{z:.1f}<extra></extra>'
        ),
    )
)
fig.update_layout(
    title='Choropleth Demo: Region-Level Data Mapped to Representative Countries',
    geo=dict(showframe=False, showcoastlines=True, projection_type='natural earth'),
    margin=dict(t=60, l=20, r=20, b=20),
)
fig.show()
sankey_df = (
    survey_df.groupby(['Group', 'SatisfactionBand', 'Recommend'], as_index=False, observed=False)
    .size()
    .rename(columns={'size': 'Count'})
)

satisfaction_nodes = [str(item) for item in survey_df['SatisfactionBand'].cat.categories]
group_nodes = list(survey_df['Group'].drop_duplicates())
recommend_nodes = list(survey_df['Recommend'].drop_duplicates())
labels = group_nodes + satisfaction_nodes + recommend_nodes
index_map = {label: idx for idx, label in enumerate(labels)}

source = []
target = []
value = []
link_color = []

for row in sankey_df.itertuples(index=False):
    band_label = str(row.SatisfactionBand)

    source.append(index_map[row.Group])
    target.append(index_map[band_label])
    value.append(row.Count)
    link_color.append('rgba(42, 157, 143, 0.35)' if row.Group == 'GenAI' else 'rgba(231, 111, 81, 0.35)')

    source.append(index_map[band_label])
    target.append(index_map[row.Recommend])
    value.append(row.Count)
    link_color.append('rgba(69, 123, 157, 0.25)')

node_colors = ['#2A9D8F', '#E76F51', '#8AB17D', '#E9C46A', '#457B9D', '#2A9D8F', '#E76F51']

fig = go.Figure(
    data=[
        go.Sankey(
            arrangement='snap',
            node=dict(label=labels, pad=18, thickness=18, color=node_colors),
            link=dict(source=source, target=target, value=value, color=link_color),
        )
    ]
)
fig.update_layout(title='Sankey Diagram: Group -> Satisfaction Band -> Recommendation', font_size=15)
fig.show()

4. Qualitative Visualizations

A word cloud is fast and approachable, but it is not the same thing as proper qualitative coding. It works well here as a low-friction classroom exercise.

transcript_df
id group text
0 1 GenAI I tried using ChatGPT to help me study for my exams. At first I was not sure, but it turned out to be extremely helpful. Whenever I had ...
1 2 GenAI I used an AI chatbot for help in my course, but it was not as great as I expected. Sometimes it gave me answers that were confusing or e...
2 3 Traditional I decided not to use any AI or online tutors while studying. I wanted to do everything myself using textbooks and class notes. It was a ...
all_text = ' '.join(item['text'] for item in transcripts)
custom_stopwords = STOPWORDS.union({'ai', 'chatgpt', 'using', 'used', 'tool', 'tools'})

wordcloud = WordCloud(
    width=900,
    height=450,
    background_color='white',
    stopwords=custom_stopwords,
    collocations=False,
).generate(all_text)

plt.figure(figsize=(12, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Word Cloud Of Transcript Text')
plt.show()

theme_keywords = {
    'Helpful AI': ['helpful', 'tutor', 'great help', 'clear explanations', 'improved'],
    'Saves time': ['time', 'quickly', 'right away', 'saved'],
    'Trust / accuracy issues': ['confusing', 'wrong', 'double-checking', 'trust'],
    'Struggle without AI': ['without any ai', 'without ai', 'challenge', 'no one to ask', 'stressed'],
}

theme_hits = []
for item in transcripts:
    text = item['text'].lower()
    for theme, keywords in theme_keywords.items():
        if any(keyword in text for keyword in keywords):
            theme_hits.append({'TranscriptID': item['id'], 'Theme': theme})

theme_df = pd.DataFrame(theme_hits).drop_duplicates()
theme_summary = (
    theme_df['Theme']
    .value_counts()
    .rename_axis('Theme')
    .reset_index(name='Mentions')
)

plt.figure(figsize=(9, 5))
sns.barplot(data=theme_summary, x='Mentions', y='Theme', hue='Theme', dodge=False, palette='crest')
ax = plt.gca()
if ax.legend_:
    ax.legend_.remove()
plt.title('Simple Theme Count From Transcript Keywords')
plt.xlabel('Number of Transcripts Mentioning The Theme')
plt.ylabel('Theme')
plt.show()

display(theme_summary)

Theme Mentions
0 Saves time 3
1 Helpful AI 2
2 Trust / accuracy issues 1
3 Struggle without AI 1

5. Student Sandbox

Change this next cell and rerun it. Suggestions: - replace Score with Satisfaction - filter to one or two regions only - swap violinplot for boxplot or stripplot - compare Recommend instead of Group - change the color palette and titles

practice_df = survey_df.query("Region in ['Asia', 'Europe', 'North America']").copy()

plt.figure(figsize=(8, 5))
ax = sns.violinplot(
    data=practice_df,
    x='Group',
    y='Score',
    hue='Group',
    dodge=False,
    inner='quartile',
    palette=palette,
)
if ax.legend_:
    ax.legend_.remove()
plt.title('Edit This Chart And See What Changes')
plt.xlabel('Learning Method')
plt.ylabel('Score')
plt.show()

6. If Students Want To Use Their Own Data

In Google Colab, they can upload a CSV and replace survey_df with their own dataframe. The quickest path is:

from google.colab import files
uploaded = files.upload()
my_file = next(iter(uploaded))
survey_df = pd.read_csv(my_file)
survey_df.head()

After that, they can adapt the plotting cells above as long as the column names match what the chart expects.

7. Beyond Colab: Plotly, Flourish, and D3.js

  • Plotly is the easiest upgrade if you already work in Python and want interactive charts.
  • Flourish is useful for quick presentation-ready interactive visuals without much code.
  • D3.js is the option to learn when you want a fully custom web visualization or scrollytelling piece.

Good next stops: - D3.js - Observable - D3 Graph Gallery

For DESN2003, the practical rule is: use notebook charts first, then move to D3.js only if the custom interaction is central to your project story.

 

DESN2003: Research for Innovation · University of Hong Kong