[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?
- "Seeing once is better than hearing a hundred times"
- One look is better than a hundred explanations.
- Visualization also plays a key role in data analysis.
- What Numbers Alone Cannot Reveal
- Patterns and Trends
- See at a glance whether data increase over time,
- decrease,
- or vary periodically.
- Relationships between Data
- Easily see whether two variables are proportional
- or inversely proportional.
- e.g., car weight and fuel efficiency
- Discovering Outliers
- Values far removed from other data
- can be easily identified visually.
- Patterns and Trends
- Anscombe's Quartet
- A famous dataset with nearly identical statistics (means, variances, etc.)
- but completely different patterns when visualized
- A classic example showing why visualization is essential in data analysis.
- Anscombe's Quartet data structure
- Stored as a Pandas DataFrame.
- Similar to a NumPy array, but with labels for rows and columns,
- like an Excel spreadsheet.
- The
anscombedataset looks as follows when you applyprint.
| 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 |
| โฆ | โฆ | โฆ | โฆ |
- Our goal
- Use the 'dataset' column
- to split the data into 4 groups (I, II, III, IV) and visualize each group.
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.
- Line Plot:
plt.plot()- Useful for showing trends in change over time.
- e.g., stock prices and temperature changes
- Useful for showing trends in change over time.
- Scatter Plot:
plt.scatter()- Useful for showing the relationship (correlation) between two variables.
- e.g., study hours and exam scores, height and weight
- Useful for showing the relationship (correlation) between two variables.
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
- Until
plt.show()is called,- All plots are drawn together on the same canvas.
- This enables rich visualizations, such as comparing data with model predictions.
# 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>
๋ ๋ชจ๋ธ์ ์์ธก ๊ฒฐ๊ณผ๋ฅผ ์ค์ ๋ฐ์ดํฐ์ ๋น๊ตํ๋ฉฐ ์ด๋ค ๋ชจ๋ธ์ด ๋ ๋์์ง ์ง๊ด์ ์ผ๋ก ํ๋จํ ์ ์์ต๋๋ค.