Matplotlib-Bubble-LineGraphs-Trends

Line Graphs & Trends in Matplotlib — Baby Steps

Keyword: matplotlib line plot • Difficulty: Beginner • Author: Champak Roy

Line graphs are the go-to chart for showing change over time and trends. In this lesson you'll learn simple line plots, multiple series, markers & styles, smoothing / moving averages (trend lines), and how to annotate important points. Try examples live below using Python (Pyodide)!

💡 Step-by-Step Tutorial

1) Import Matplotlib

import matplotlib.pyplot as plt

2) Prepare your data

months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug']
sales = [120, 130, 115, 150, 170, 165, 180, 190]

3) Draw your first line chart

plt.plot(months, sales)
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.show()

4) Multiple series & styles

plt.plot(months, sales, marker='o', linestyle='-', label='This Year')
plt.plot(months, [100,110,120,130,140,150,160,170], marker='s', linestyle='--', label='Last Year')
plt.legend()

5) Markers, colors and grids

plt.plot(months, sales, color='#2b9bd3', marker='o', linewidth=2)
plt.grid(alpha=0.3)

6) Trend line — moving average (simple)

import numpy as np
window = 3
movavg = np.convolve(sales, np.ones(window)/window, mode='valid')
# plot movavg aligned to the middle of the window
plt.plot(months[window-1:], movavg, color='orange', label='3-month MA')

7) Annotate points

plt.annotate('Peak', xy=('Aug', 190), xytext=('Jun',200),
             arrowprops=dict(arrowstyle='->'))

💬 Tip: In the Pyodide practice section below, use matplotlib.use('Agg') and save your figure with plt.savefig() to display it in-browser.

📊 Sample static output: sample line chart

🧪 Practice: Run Matplotlib with Pyodide

Click Preload Pyodide once to install matplotlib and numpy. Then press Run & Render to display your chart as an image!

Idle
Console output:
No chart yet — run code to render a PNG here.

🧠 Tips & Notes

  • Use plt.plot() for continuous data — ideal for time series and trends.
  • Plot multiple series to compare (this year vs last year) — use label and plt.legend().
  • Use moving averages or smoothing to emphasise trend over noise.
  • Annotate important points with plt.annotate() to call out peaks or events.
  • If Pyodide fails to load: refresh, try Incognito, or follow the site instructions to preload Pyodide in the theme.
© Learning Sutras — Champak Roy | Made with 💙 in Varanasi

0 Comments

Post a Comment

0 Comments