0Pricing
Pandas & NumPy Academy · Ders

Çizgi ve Dağılım Grafikleri

Sürekli verileri ax.plot() ile, ayrık noktaları ax.scatter() ile çizin; rengi, işaretçiyi ve çizgi stilini denetleyin.

Çizgi ve Dağılım Grafikleri, CoddyKit'te ücretsiz bir Pandas & NumPy Academy dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Pandas & NumPy Academy öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Pandas & NumPy Academy kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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.

Sıkça Sorulan Sorular

“Çizgi ve Dağılım Grafikleri” dersi ücretsiz mi?

Evet — “Çizgi ve Dağılım Grafikleri” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Pandas & NumPy Academy kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Pandas & NumPy Academy kursu toplamda 4 dersten oluşur.

“Çizgi ve Dağılım Grafikleri” dersinde ne öğreneceğim?

Sürekli verileri ax.plot() ile, ayrık noktaları ax.scatter() ile çizin; rengi, işaretçiyi ve çizgi stilini denetleyin. Pandas & NumPy Academy ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Pandas & NumPy Academy öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Pandas & NumPy Academy, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Çizgi ve Dağılım Grafikleri” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Pandas & NumPy Academy dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Pandas & NumPy Academy dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Şekil ve Eksen Mimarisi
  2. Çizgi ve Dağılım Grafikleri
  3. Çubuk Grafikler ve Histogramlar
  4. Etiketler, Başlıklar ve Şekilleri Kaydetme
← Pandas & NumPy Academy Sayfasına Dön