גרפים עם matplotlibCharts with matplotlib
קו, עמודות, עוגה ושמירה לקובץ.
Line, bar, pie and saving to a file.
גרף טמפרטורותA temperature chart
תזכורת: מה ביקשוReminder: the task
ציירו גרף קו של הטמפרטורות לפי יום, עם כותרת Week temperatures, תווית °C לציר y, ונקודות (marker="o"). שמרו ל-temps.png.
Draw a line chart of temperatures by day, with the title Week temperatures, a °C y-label, and dots (marker="o"). Save to temps.png.
הפתרון המלא והפלט שלוFull solution and its output
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
temps = [24, 26, 25, 29, 31, 28, 27]
fig, ax = plt.subplots()
ax.plot(days, temps, marker="o")
ax.set_title("Week temperatures")
ax.set_ylabel("°C")
fig.savefig("temps.png")יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עמודות עם ערכיםBars with values
תזכורת: מה ביקשוReminder: the task
ציירו גרף עמודות של מכירות לפי מוצר, עם ערך מעל כל עמודה (bar_label), והעמודה הגבוהה ביותר בצבע #d7263d (השאר #999999).
Draw a bar chart of sales per product, with a value over each bar (bar_label), and the tallest bar in #d7263d (the rest #999999).
הפתרון המלא והפלט שלוFull solution and its output
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
products = ["pens", "books", "bags"]
sales = [120, 340, 90]
colors = ["#d7263d" if s == max(sales) else "#999999" for s in sales]
fig, ax = plt.subplots()
bars = ax.bar(products, sales, color=colors)
ax.bar_label(bars)
fig.savefig("sales.png")יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שני קווים ומקראTwo lines and a legend
תזכורת: מה ביקשוReminder: the task
ציירו שני קווים, 2025 ו-2026, של ספרים לפי רבעון, עם מקרא (label=) וכותרת Books per quarter.
Draw two lines, 2025 and 2026, of books per quarter, with a legend (label=) and the title Books per quarter.
הפתרון המלא והפלט שלוFull solution and its output
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
q = ["Q1", "Q2", "Q3", "Q4"]
y2025 = [3, 5, 2, 6]
y2026 = [4, 4, 6, 7]
fig, ax = plt.subplots()
ax.plot(q, y2025, label="2025")
ax.plot(q, y2026, label="2026")
ax.set_title("Books per quarter")
ax.legend()
fig.savefig("quarters.png")יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
היסטוגרמהA histogram
תזכורת: מה ביקשוReminder: the task
ציירו היסטוגרמה של אורכי הספרים עם 4 סלים (bins=4), והדפיסו כמה ספרים יש בכל סל (ax.hist מחזיר את הספירות כאיבר הראשון).
Draw a histogram of book lengths with 4 bins (bins=4), and print how many books are in each bin (ax.hist returns the counts as its first item).
הפתרון המלא והפלט שלוFull solution and its output
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
pages = [96, 180, 208, 240, 249, 310, 412, 474, 520, 610]
fig, ax = plt.subplots()
counts, edges, _ = ax.hist(pages, bins=4)
print([int(c) for c in counts])
fig.savefig("hist.png")[3, 3, 2, 2]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 25: גרף קריאה חודשיShelf, step 25: a monthly reading chart
תזכורת: מה ביקשוReminder: the task
כתבו reading_chart(books, path) שמקבלת רשימת מילונים עם month ו-pages, מסכמת עמודים לפי חודש (בסדר Jan עד Jun, 0 לחודש בלי קריאה), מציירת עמודות עם ערכים, מדגישה את החודש הטוב ביותר, שומרת ל-path ומחזירה את שם החודש הטוב.
Write reading_chart(books, path) taking a list of dicts with month and pages, totalling pages per month (in order Jan to Jun, 0 for a month without reading), drawing bars with values, highlighting the best month, saving to path and returning the best month's name.
הפתרון המלא והפלט שלוFull solution and its output
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
def reading_chart(books, path):
totals = {m: 0 for m in MONTHS}
for b in books:
totals[b["month"]] += b["pages"]
best = max(totals, key=totals.get)
colors = ["#2d5bd0" if m == best else "#b8c2d6" for m in MONTHS]
fig, ax = plt.subplots(figsize=(6, 3))
bars = ax.bar(MONTHS, [totals[m] for m in MONTHS], color=colors)
ax.bar_label(bars)
ax.set_title(f"Pages per month (best: {best})")
fig.savefig(path, bbox_inches="tight")
return best
shelf = [{"month": "Jan", "pages": 412}, {"month": "Feb", "pages": 474}, {"month": "Feb", "pages": 240}, {"month": "Apr", "pages": 249}]
print(reading_chart(shelf, "reading.png"))Feb
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לוח מחוונים קטןA small dashboard
תזכורת: מה ביקשוReminder: the task
צרו Figure עם 3 גרפים בשורה (plt.subplots(1, 3)): עמודות של ספרים לפי סופר (מ-Counter), היסטוגרמה של עמודים, ופיזור של עמודים מול דירוג. לכל גרף כותרת. החזירו מ-dashboard(books) את ה-Figure.
Create a Figure with 3 charts in a row (plt.subplots(1, 3)): bars of books per author (from Counter), a histogram of pages, and a scatter of pages against rating. Each chart gets a title. Return the Figure from dashboard(books).
הפתרון המלא והפלט שלוFull solution and its output
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from collections import Counter
def dashboard(books):
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 3))
counts = Counter(b["author"] for b in books)
ax1.bar(list(counts), list(counts.values()))
ax1.set_title("Books per author")
ax2.hist([b["pages"] for b in books], bins=3)
ax2.set_title("Pages")
ax3.scatter([b["pages"] for b in books], [b["rating"] for b in books])
ax3.set_title("Pages vs rating")
fig.tight_layout()
return fig
books = [{"author": "Dahl", "pages": 240, "rating": 5}, {"author": "Dahl", "pages": 208, "rating": 4}, {"author": "Austen", "pages": 474, "rating": 3}]
fig = dashboard(books)
fig.savefig("dash.png")
print(len(fig.axes), [ax.get_title() for ax in fig.axes])3 ['Books per author', 'Pages', 'Pages vs rating']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ממוצע נעA moving average
תזכורת: מה ביקשוReminder: the task
כתבו moving_avg(values, k) שמחזירה ממוצע נע של k ערכים (רשימה קצרה ב-k-1 מהמקור, מעוגל ל-1), וציירו גם את הנתונים המקוריים (נקודות אפורות) וגם את הממוצע הנע (קו בולט) על אותו גרף, עם מקרא.
Write moving_avg(values, k) returning a k-value moving average (a list k-1 shorter than the input, rounded to 1), and draw both the raw data (grey dots) and the moving average (a bold line) on the same chart, with a legend.
הפתרון המלא והפלט שלוFull solution and its output
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def moving_avg(values, k):
return [round(sum(values[i:i + k]) / k, 1) for i in range(len(values) - k + 1)]
pages = [40, 10, 55, 30, 70, 20, 65, 50]
avg = moving_avg(pages, 3)
fig, ax = plt.subplots()
ax.plot(range(len(pages)), pages, "o", color="#999999", label="daily")
ax.plot(range(2, len(pages)), avg, linewidth=3, label="3-day average")
ax.legend()
fig.savefig("smooth.png")
print(avg)[35.0, 31.7, 51.7, 40.0, 51.7, 45.0]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.