Course materials ยท Introduction to Machine Learning

[Week 6] Bringing Data to Life! Matplotlib Visualization ๐Ÿ“Š

English translation

Hello! Welcome to Week 6, our final session on Python basics.

So far, we have used Python and NumPy to

We have learned how to store data and perform calculations.

Data filled only with numbers do not tell us a story on their own.

Today, using Matplotlib, a key library for data analysis,

We will learn visualization, turning data into visible graphics.

How visualization can reveal hidden patterns and insights in data,

Check for yourself!

๐Ÿ‘€ Module 1: Why Look at Data Visually?

No. dataset x y
0 I 10.0 8.04
1 I 8.0 6.95
โ€ฆ โ€ฆ โ€ฆ โ€ฆ
10 I 5.0 5.68
11 II 10.0 9.14
โ€ฆ โ€ฆ โ€ฆ โ€ฆ
import matplotlib.pyplot as plt
import seaborn as sns
# A library providing example datasets

# 1. Load Anscombe's quartet dataset (as a Pandas DataFrame)
anscombe = sns.load_dataset("anscombe")

# 2. Inspect the dataset structure
print("--- ์ „์ฒด ๋ฐ์ดํ„ฐ์…‹ (์•ž 5์ค„) ---")
print(anscombe.head())
print("\n--- ํ†ต๊ณ„ ์ˆ˜์น˜ ์š”์•ฝ ---")
# Group by the 'dataset' column and calculate statistics for each group
print(anscombe.groupby('dataset').describe())
print("\n=> ๋ชจ๋“  ๋ฐ์ดํ„ฐ์…‹์˜ ํ‰๊ท (mean), ํ‘œ์ค€ํŽธ์ฐจ(std) ๋“ฑ ํ†ต๊ณ„์น˜๊ฐ€ ๊ฑฐ์˜ ๋™์ผํ•ฉ๋‹ˆ๋‹ค.")

# 3. Split the data (Boolean Indexing)
# anscombe['dataset'] == 'I'
# >> Return True for rows where the 'dataset' column equals 'I', and False otherwise
# anscombe[ ... ]
# >> Select only the rows marked True above from the full DataFrame
df1 = anscombe[anscombe['dataset'] == 'I']
df2 = anscombe[anscombe['dataset'] == 'II']
df3 = anscombe[anscombe['dataset'] == 'III']
df4 = anscombe[anscombe['dataset'] == 'IV']
--- ์ „์ฒด ๋ฐ์ดํ„ฐ์…‹ (์•ž 5์ค„) ---
  dataset     x     y
0       I  10.0  8.04
1       I   8.0  6.95
2       I  13.0  7.58
3       I   9.0  8.81
4       I  11.0  8.33

--- ํ†ต๊ณ„ ์ˆ˜์น˜ ์š”์•ฝ ---
            x                                               y            \
        count mean       std  min  25%  50%   75%   max count      mean   
dataset                                                                   
I        11.0  9.0  3.316625  4.0  6.5  9.0  11.5  14.0  11.0  7.500909   
II       11.0  9.0  3.316625  4.0  6.5  9.0  11.5  14.0  11.0  7.500909   
III      11.0  9.0  3.316625  4.0  6.5  9.0  11.5  14.0  11.0  7.500000   
IV       11.0  9.0  3.316625  8.0  8.0  8.0   8.0  19.0  11.0  7.500909   

                                                   
              std   min    25%   50%   75%    max  
dataset                                            
I        2.031568  4.26  6.315  7.58  8.57  10.84  
II       2.031657  3.10  6.695  8.14  8.95   9.26  
III      2.030424  5.39  6.250  7.11  7.98  12.74  
IV       2.030579  5.25  6.170  7.04  8.19  12.50  

=> ๋ชจ๋“  ๋ฐ์ดํ„ฐ์…‹์˜ ํ‰๊ท (mean), ํ‘œ์ค€ํŽธ์ฐจ(std) ๋“ฑ ํ†ต๊ณ„์น˜๊ฐ€ ๊ฑฐ์˜ ๋™์ผํ•ฉ๋‹ˆ๋‹ค.
# Visualize the 4 datasets
# plt.subplots
# >> Create multiple small plots (axes) within one figure
fig, axes = plt.subplots(2, 2, figsize=(6, 8))
axes[0, 0].scatter(df1['x'], df1['y'])
axes[0, 0].set_title("Dataset I")
axes[0 ,1].scatter(df2['x'], df2['y'])
axes[0, 1].set_title("Dataset II")
axes[1, 0].scatter(df3['x'], df3['y'])
axes[1, 0].set_title("Dataset III")
axes[1, 1].scatter(df4['x'], df4['y'])
axes[1, 1].set_title("Dataset IV")

plt.show()
print("\nโœจ ๊ฒฐ๊ณผ: ํ•˜์ง€๋งŒ ์‹œ๊ฐํ™”ํ•ด๋ณด๋‹ˆ, ๋„ค ๋ฐ์ดํ„ฐ์…‹์€ ์™„์ „ํžˆ ๋‹ค๋ฅธ ํŒจํ„ด์„ ๊ฐ€์ง€๊ณ  ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค!")
<Figure size 600x800 with 4 Axes>
์‹คํ–‰ ๊ฒฐ๊ณผ
โœจ ๊ฒฐ๊ณผ: ํ•˜์ง€๋งŒ ์‹œ๊ฐํ™”ํ•ด๋ณด๋‹ˆ, ๋„ค ๋ฐ์ดํ„ฐ์…‹์€ ์™„์ „ํžˆ ๋‹ค๋ฅธ ํŒจํ„ด์„ ๊ฐ€์ง€๊ณ  ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค!

๐Ÿ“ˆ Module 2: Basic Plotting with Matplotlib

Matplotlib can create many types of graphs, but

Today we will learn two basic but important types of plot.

  1. Line Plot: plt.plot()
    • Useful for showing trends in change over time.
      • e.g., stock prices and temperature changes
  2. Scatter Plot: plt.scatter()
    • Useful for showing the relationship (correlation) between two variables.
      • e.g., study hours and exam scores, height and weight
import numpy as np

# Prepare data: Months 1 through 12 and mean temperatures
months = np.arange(1, 13)
temperatures = np.array([0, 2, 8, 14, 20, 25, 28, 27, 22, 15, 7, 1])

# 1. Prepare the plotting canvas (figure)
# figsize=(6, 4) specifies a canvas 6 inches wide and 4 inches high.
# Changing the numbers changes the plot size.
plt.figure(figsize=(6, 4))

# 2. Draw a line plot (plot)
# plt.plot(x์ถ•_๋ฐ์ดํ„ฐ, y์ถ•_๋ฐ์ดํ„ฐ)
# color: Line color ('blue', 'red', 'g', 'k', etc.)
# linestyle: Line style ('-' solid, '--' dashed, ':' dotted)
# marker: Shape marking each data point ('o' circle, 's' square, 'x')
# label: The name shown in the legend to identify this line
plt.plot(months, temperatures,
         color='red',
         linestyle='--',
         marker='o',
         label='Avg Temperature')

# 3. Format the plot
plt.title("Monthly Average Temperature") # Title
plt.xlabel("Month") # x-axis label
plt.ylabel("Temperature (ยฐC)") # y-axis label
plt.grid(True) # Add grid lines
plt.legend() # Add a legend showing the label

# 4. Display the plot
plt.show()
<Figure size 600x400 with 1 Axes>
์‹คํ–‰ ๊ฒฐ๊ณผ
# Prepare data: Students' study hours and exam scores
study_hours = np.array([2, 3, 4.5, 6, 7.5, 8, 9])
exam_scores = np.array([65, 70, 78, 85, 90, 92, 97])

# 1. Prepare the canvas
plt.figure(figsize=(6, 4))

# 2. Draw a scatter plot (scatter)
# plt.scatter(x์ถ•_๋ฐ์ดํ„ฐ, y์ถ•_๋ฐ์ดํ„ฐ)
# s: Point size
# c: Point color
# alpha: Point transparency (0.0 ~ 1.0). Useful when points overlap.
plt.scatter(study_hours, exam_scores,
            s=100,
            c='blue',
            alpha=0.6,
            label='Student Scores')

# 3. Format the plot
plt.title("Study Hours vs Exam Scores")
plt.xlabel("Study Hours")
plt.ylabel("Exam Scores")
plt.grid(True)
plt.legend()

# 4. Display the plot
plt.show()
<Figure size 600x400 with 1 Axes>
์‹คํ–‰ ๊ฒฐ๊ณผ

๐ŸŽจ Module 3: Overlaying Multiple Plots

# Actual data
study_hours = np.array([2, 3, 4.5, 6, 7.5, 8, 9])
exam_scores = np.array([65, 70, 78, 85, 90, 92, 97])

# Two hypothetical prediction models
# Model 1: A model with poor predictions
W1, b1 = 3, 65
predicted1 = W1 * study_hours + b1
# Model 2: A model with relatively good predictions
W2, b2 = 4, 60
predicted2 = W2 * study_hours + b2

# --- Overlay plots ---
plt.figure(figsize=(6, 4))

# 1. Plot actual data as a scatter plot (baseline)
plt.scatter(study_hours, exam_scores,
            c='black', s=100, label='Actual Data')

# 2. Plot model 1's predictions as a red dashed line
plt.plot(study_hours, predicted1,
         color='red', linestyle=':',
         label='Model 1 (Bad Fit)')

# 3. Plot model 2's predictions as a blue solid line
plt.plot(study_hours, predicted2,
         color='blue', linestyle='-',
         label='Model 2 (Good Fit)')

# 4. Format the plot
plt.title("Actual Data vs. Model Predictions")
plt.xlabel("Study Hours")
plt.ylabel("Exam Scores")
plt.grid(True)
plt.legend()

# 5. Display the plot
plt.show()
print("๋‘ ๋ชจ๋ธ์˜ ์˜ˆ์ธก ๊ฒฐ๊ณผ๋ฅผ ์‹ค์ œ ๋ฐ์ดํ„ฐ์™€ ๋น„๊ตํ•˜๋ฉฐ ์–ด๋–ค ๋ชจ๋ธ์ด ๋” ๋‚˜์€์ง€ ์ง๊ด€์ ์œผ๋กœ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
<Figure size 600x400 with 1 Axes>
์‹คํ–‰ ๊ฒฐ๊ณผ
๋‘ ๋ชจ๋ธ์˜ ์˜ˆ์ธก ๊ฒฐ๊ณผ๋ฅผ ์‹ค์ œ ๋ฐ์ดํ„ฐ์™€ ๋น„๊ตํ•˜๋ฉฐ ์–ด๋–ค ๋ชจ๋ธ์ด ๋” ๋‚˜์€์ง€ ์ง๊ด€์ ์œผ๋กœ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.