선 그래프와 산점도
ax.plot()으로 연속형 데이터를, ax.scatter()로 이산적인 점을 그리며 색상, 마커, 선 스타일을 제어합니다.
선 그래프와 산점도은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Line and Scatter: Core Plot Types
Line plots connect sequential data points with a line and are ideal for visualising trends over time or continuous functions. Scatter plots draw individual points without connecting lines, making them perfect for exploring relationships between two numeric variables. Both are created on a Matplotlib Axes object: ax.plot() for lines and ax.scatter() for scatter points.
ax.plot() for Line Charts
ax.plot(x, y) draws a line connecting data points in order. Pass x-values as the first argument and y-values as the second. Both can be Python lists, NumPy arrays, or Pandas Series. When only one argument is passed, Matplotlib uses the index (0, 1, 2, ...) as the x-axis automatically. The method returns a list of Line2D Artist objects.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, y) # basic line plot
ax.set_title('Sine Wave')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
# plt.show()
plt.close()Controlling Line Style and Colour
The most common ax.plot() keyword arguments: color (name, hex, or RGB tuple), linewidth (or lw), linestyle (or ls): '-' solid, '--' dashed, ':' dotted, '-.' dash-dot, marker (shape at each data point), and markersize. Combine linestyle and marker to show both the line and the individual data points simultaneously.
fig, ax = plt.subplots(figsize=(7, 4))
# Solid blue line with circle markers
ax.plot(x, np.sin(x), color='steelblue', lw=2, ls='-',
marker='o', markersize=4, label='sin(x)')
# Dashed red line
ax.plot(x, np.cos(x), color='crimson', lw=1.5, ls='--', label='cos(x)')
ax.legend()
plt.close()Plotting Multiple Lines
Call ax.plot() multiple times to overlay several lines on the same Axes. Matplotlib automatically cycles through a default colour palette. Always pass the label keyword for each line so ax.legend() can label them automatically. Place the legend call after all plot calls to ensure all lines are included.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
dates = pd.date_range('2024-01', periods=12, freq='ME')
fig, ax = plt.subplots(figsize=(8, 4))
for product in ['A', 'B', 'C']:
sales = np.random.randint(50, 200, 12)
ax.plot(dates, sales, marker='o', label=f'Product {product}')
ax.set_title('Monthly Sales by Product')
ax.legend()
plt.close()Plotting Pandas DataFrames Directly
Pandas DataFrames have a .plot() method that creates Matplotlib charts directly. Pass ax=ax to draw on an existing Axes object. df.plot(ax=ax) plots all columns as separate lines using the DataFrame index as the x-axis. You can still apply all Matplotlib customisations on the ax object afterward.
df = pd.DataFrame(
np.random.randn(12, 3),
index=pd.date_range('2024', periods=12, freq='ME'),
columns=['North', 'South', 'West']
).cumsum()
fig, ax = plt.subplots(figsize=(8, 4))
df.plot(ax=ax, linewidth=1.5)
ax.set_title('Cumulative Revenue by Region')
ax.set_ylabel('Revenue (cumulative)')
plt.close()ax.scatter() for Scatter Plots
ax.scatter(x, y) draws individual points without connecting lines. Unlike ax.plot(), scatter does not assume the data is ordered. Key parameters: c (colour, can be an array for per-point colouring), s (point size, can also be an array), cmap (colourmap for when c is numeric), alpha (transparency 0-1 to handle overplotting).
np.random.seed(42)
x = np.random.randn(100)
y = 2 * x + np.random.randn(100)
fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(x, y, color='steelblue', alpha=0.6, s=40)
ax.set_xlabel('Feature X')
ax.set_ylabel('Target Y')
ax.set_title('Feature vs Target')
plt.close()Colouring Scatter Points by Category
Pass a numeric array to the c parameter and a cmap colourmap to colour scatter points by a third variable. Add a colourbar with plt.colorbar(scatter_obj) to provide a scale. This technique is called a bubble chart variant when the s (size) parameter is also varied by a fourth variable.
categories = np.random.choice([0, 1, 2], size=100)
fig, ax = plt.subplots(figsize=(6, 5))
scatter = ax.scatter(x, y, c=categories, cmap='Set1',
alpha=0.7, s=60, edgecolors='none')
fig.colorbar(scatter, ax=ax, label='Category')
ax.set_title('Scatter Coloured by Category')
plt.close()Adding a Trend Line
A scatter plot with a fitted trend line communicates both the individual data points and the overall pattern. Use np.polyfit(x, y, 1) to compute a linear fit, evaluate it with np.poly1d(coeffs)(x_range), and overlay the result with ax.plot() on top of the scatter. The trend line should be thinner and styled differently to distinguish it from data points.
fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(x, y, alpha=0.4, s=30, color='steelblue', label='Data')
# Fit and plot linear trend line
coeffs = np.polyfit(x, y, 1)
x_line = np.linspace(x.min(), x.max(), 100)
y_line = np.poly1d(coeffs)(x_line)
ax.plot(x_line, y_line, color='red', lw=2, label='Linear fit')
ax.legend()
ax.set_title('Scatter with Trend Line')
plt.close()Shading Confidence Bands with fill_between
ax.fill_between(x, y_lower, y_upper) fills the area between two curves. This is commonly used to show confidence intervals around a mean line, standard deviation bands, or min/max envelopes. Pass alpha to make the shading semi-transparent so the underlying data remains visible.
x_range = np.linspace(0, 2 * np.pi, 100)
mean = np.sin(x_range)
upper = mean + 0.2
lower = mean - 0.2
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x_range, mean, color='steelblue', lw=2, label='Mean')
ax.fill_between(x_range, lower, upper,
color='steelblue', alpha=0.2, label='±0.2 band')
ax.legend()
ax.set_title('Line with Confidence Band')
plt.close()Axis Limits and Grid Lines
Control the visible range with ax.set_xlim(min, max) and ax.set_ylim(min, max). Enable grid lines with ax.grid(True). Customise the grid with keyword arguments: linestyle, linewidth, alpha. A subtle grid with alpha=0.3 aids reading exact values without cluttering the chart. Call ax.set_axisbelow(True) to draw the grid behind data points.
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, np.sin(x), 'b-', lw=2)
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1.2, 1.2)
ax.grid(True, linestyle='--', alpha=0.5)
ax.set_axisbelow(True) # grid behind data
ax.set_title('Sine with Grid')
plt.close()Alpha and Overplotting
When many data points overlap in the same region of a scatter plot, individual points become invisible — this is called overplotting. The simplest fix is to reduce opacity with alpha (0.0 = fully transparent, 1.0 = fully opaque). Set alpha=0.3 or lower so that dense regions appear darker (because multiple semi-transparent points stack up) while sparse regions remain light. For very large datasets (millions of points), consider hexbin or kernel density estimates instead.
np.random.seed(1)
x_dense = np.random.randn(1000)
y_dense = np.random.randn(1000)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# Without alpha: overplotting hides density
ax1.scatter(x_dense, y_dense, s=10)
ax1.set_title('No alpha (overplotted)')
# With alpha: density visible
ax2.scatter(x_dense, y_dense, s=10, alpha=0.2)
ax2.set_title('alpha=0.2 (density visible)')
plt.tight_layout()
plt.close()Quick Check
Test your understanding of line and scatter plots in Matplotlib from this lesson.
Lesson Recap
In this lesson you learned: ax.plot() creates line charts with full control over colour, line style, and markers; ax.scatter() creates scatter plots with per-point colour and size via c and s; ax.fill_between() adds confidence bands; and ax.grid() adds grid lines for readability. Next up we create bar charts and histograms to visualise categorical and distributional data.
자주 묻는 질문
“선 그래프와 산점도” 강의는 무료인가요?
네 — “선 그래프와 산점도” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“선 그래프와 산점도”에서 뭘 배우나요?
ax.plot()으로 연속형 데이터를, ax.scatter()로 이산적인 점을 그리며 색상, 마커, 선 스타일을 제어합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“선 그래프와 산점도” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.