נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
25
חלקPart 4: נתונים ורשתData & the web כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

גרפים עם matplotlibCharts with matplotlib

קו, עמודות, עוגה ושמירה לקובץ.

Line, bar, pie and saving to a file.

01גרף ראשוןYour first chart

matplotlib מצייר גרפים מקוד. יוצרים Figure ו-Axes עם plt.subplots(), ומציירים על ה-Axes. ax.plot(x, y) מצייר קו שמחבר את הנקודות. ב-VS Code, plt.show() פותח חלון; כאן שומרים לקובץ עם savefig, והתמונה מופיעה מתחת לקוד. (שתי השורות הראשונות מוודאות שהציור עובד גם בלי מסך.)

matplotlib draws charts from code. Create a Figure and Axes with plt.subplots(), and draw on the Axes. ax.plot(x, y) draws a line joining the points. In VS Code, plt.show() opens a window; here we save to a file with savefig, and the image appears under the code. (The first two lines make drawing work even without a screen.)

first_chart.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
pages = [412, 714, 518, 249, 600, 380]

fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(months, pages, marker="o")
fig.savefig("pages.png", dpi=80, bbox_inches="tight")
print("saved")
פלטOutput
saved
גרף קו של עמודים לפי חודש: עולה לשיא בפברואר, יורד באפריל, ועולה שוב במאי.
pages.png
אנלוגיה מהחייםReal-life analogy

Figure הוא דף ציור, Axes הוא מסגרת שמשרטטים בתוכה. אפשר לשים כמה מסגרות על אותו דף.

The Figure is a sheet of drawing paper, an Axes is a frame you draw inside. One sheet can hold several frames.

טעות נפוצהCommon mistake

שתי רשימות באורך שונה.

Two lists of different lengths.

first_chart.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(["Jan", "Feb", "Mar"], [412, 714])
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/first_chart.py", line 6, in <module>
    ax.plot(["Jan", "Feb", "Mar"], [412, 714])
    ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/site-packages/matplotlib/axes/_axes.py", line 1792, in plot
    lines = [*self._get_lines(self, *args, data=data, **kwargs)]
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/site-packages/matplotlib/axes/_base.py", line 331, in __call__
    yield from self._plot_args(
               ~~~~~~~~~~~~~~~^
        axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        return_kwargs=return_kwargs
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/usr/local/lib/python3.13/site-packages/matplotlib/axes/_base.py", line 509, in _plot_args
    raise ValueError(f"x and y must have same first dimension, but "
                     f"have shapes {x.shape} and {y.shape}")
ValueError: x and y must have same first dimension, but have shapes (3,) and (2,)
בעברית פשוטה: In plain words: ValueError: x and y must have same first dimension, but have shapes (3,) and (2,): לכל x צריך y. בודקים את אורך שתי הרשימות.ValueError: x and y must have same first dimension, but have shapes (3,) and (2,): every x needs a y. Check both lists' lengths.

02כותרת, צירים ומקראTitle, axes and legend

גרף בלי כותרת ויחידות הוא חידה. set_title נותן כותרת, set_xlabel ו-set_ylabel מסבירים את הצירים. כשיש כמה קווים, נותנים לכל אחד label= וקוראים ל-ax.legend() כדי להציג מקרא.

A chart without a title and units is a riddle. set_title gives a title, set_xlabel and set_ylabel explain the axes. With several lines, give each a label= and call ax.legend() to show a legend.

labels.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
noa = [412, 714, 518, 249, 600, 380]
avi = [300, 280, 450, 520, 410, 610]

fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(months, noa, marker="o", label="Noa")
ax.plot(months, avi, marker="s", label="Avi")
ax.set_title("Pages read per month")
ax.set_xlabel("Month")
ax.set_ylabel("Pages")
ax.legend()
fig.savefig("compare.png", dpi=80, bbox_inches="tight")
פלטOutput
 
שני קווים, Noa ו-Avi, עמודים לפי חודש עם כותרת, צירים ומקרא. אצל Avi הקו עולה לקראת יוני.
compare.png
אנלוגיה מהחייםReal-life analogy

מקרא הוא כמו מפתח במפה: בלעדיו, קו כחול וקו כתום הם סתם קווים.

A legend is like a map key: without it, a blue line and an orange line are just lines.

טעות נפוצהCommon mistake

קוראים ל-ax.legend() בלי שנתתם label לאף קו.

Calling ax.legend() without giving any line a label.

labels.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

import warnings
warnings.simplefilter("error")
fig, ax = plt.subplots()
ax.plot([1, 2], [3, 4])
ax.legend()
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/labels.py", line 9, in <module>
    ax.legend()
    ~~~~~~~~~^^
  File "/usr/local/lib/python3.13/site-packages/matplotlib/axes/_axes.py", line 351, in legend
    handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs)
                              ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/site-packages/matplotlib/legend.py", line 1380, in _parse_legend_args
    _api.warn_external(
    ~~~~~~~~~~~~~~~~~~^
        "No artists with labels found to put in legend.  Note that "
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        "artists whose label start with an underscore are ignored "
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        "when legend() is called with no argument.")
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/site-packages/matplotlib/_api/__init__.py", line 494, in warn_external
    warnings.warn(message, category, **kwargs)
    ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UserWarning: No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
בעברית פשוטה: In plain words: UserWarning: No artists with labels found to put in legend.: (כאן הפכנו את האזהרה לשגיאה כדי שתבלוט.) מוסיפים label="..." ל-plot.UserWarning: No artists with labels found to put in legend.: (here we turned the warning into an error so it stands out.) Add label="..." to plot.

לפני שמציירים, מחשבים את הערכים.

Before drawing, work out the values.

עוד דוגמה: מכינים נתונים לגרףOne more: getting data ready for a chart
example.py
days = ["Sun", "Mon", "Tue"]
steps = [4200, 8100, 6000]
best = max(zip(steps, days))
print("best day:", best[1], best[0])
print("average:", sum(steps) // len(steps))
פלטOutput
best day: Mon 8100
average: 6100
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03איזה גרף לאיזו שאלהWhich chart for which question

הגרף הנכון תלוי בשאלה. מגמה לאורך זמן: קו. השוואה בין קבוצות: עמודות (ax.bar, ולשמות ארוכים ax.barh לרוחב). קשר בין שני מספרים, למשל עמודים ודירוג: פיזור (ax.scatter). ועוגה כמעט אף פעם, כי העין משווה אורכים הרבה יותר טוב מזוויות.

The right chart depends on the question. A trend over time: line. Comparing groups: bars (ax.bar, and for long names ax.barh sideways). A relation between two numbers, like pages and rating: scatter (ax.scatter). And a pie almost never, because the eye compares lengths far better than angles.

kinds.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

authors = ["Austen", "Dahl", "Herbert", "Tolkien"]
pages = [723, 448, 412, 310]

fig, (left, right) = plt.subplots(1, 2, figsize=(8, 3))
left.barh(authors, pages, color="#2d5bd0")
left.invert_yaxis()
left.set_title("Pages by author")
right.scatter([412, 474, 240, 208, 310, 249], [5, 3, 5, 4, 5, 4], color="#0e9f8e")
right.set_xlabel("Pages")
right.set_ylabel("Rating")
right.set_title("Longer = better?")
fig.savefig("kinds.png", dpi=80, bbox_inches="tight")
פלטOutput
 
משמאל עמודות אופקיות של עמודים לפי סופר, Austen הכי ארוכה. מימין פיזור של עמודים מול דירוג, בלי קשר ברור.
kinds.png
אנלוגיה מהחייםReal-life analogy

לבחור גרף זה כמו לבחור כלי: אפשר לדפוק מסמר עם מברג, אבל פטיש עושה את זה טוב יותר.

Choosing a chart is like choosing a tool: you can drive a nail with a screwdriver, but a hammer does it better.

טעות נפוצהCommon mistake

מספר שמות שונה ממספר הגבהים.

A different number of names and heights.

kinds.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar(["Dune", "Emma"], [412, 474, 240])
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/usr/local/lib/python3.13/site-packages/matplotlib/axes/_axes.py", line 2523, in bar
    x, height, width, y, linewidth, hatch = np.broadcast_arrays(
                                            ~~~~~~~~~~~~~~~~~~~^
        # Make args iterable too.
        ^^^^^^^^^^^^^^^^^^^^^^^^^
        np.atleast_1d(x), height, width, y, linewidth, hatch
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/usr/local/lib/python3.13/site-packages/numpy/lib/_stride_tricks_impl.py", line 651, in broadcast_arrays
    shape = _broadcast_shape(*args)
  File "/usr/local/lib/python3.13/site-packages/numpy/lib/_stride_tricks_impl.py", line 526, in _broadcast_shape
    b = np.broadcast(*args[:64])
ValueError: shape mismatch: objects cannot be broadcast to a single shape.  Mismatch is between arg 0 with shape (2,) and arg 1 with shape (3,).

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/you/python-course/kinds.py", line 6, in <module>
    ax.bar(["Dune", "Emma"], [412, 474, 240])
    ~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/site-packages/matplotlib/__init__.py", line 1531, in inner
    return func(
        ax,
        *map(cbook.sanitize_sequence, args),
        **{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})
  File "/usr/local/lib/python3.13/site-packages/matplotlib/axes/_axes.py", line 2540, in bar
    raise ValueError(error_message) from e
ValueError: shape mismatch: objects cannot be broadcast to a single shape.  Mismatch is between 'x' with shape (2,) and 'height' with shape (3,).
בעברית פשוטה: In plain words: ValueError: shape mismatch: לכל עמודה צריך גובה אחד. בודקים ששתי הרשימות באותו אורך.ValueError: shape mismatch: every bar needs one height. Check both lists have the same length.

04עיצוב שעוזר לקרואStyling that helps reading

עיצוב טוב לא מקשט, הוא עוזר לקרוא. צבע אחד לכל העמודות, וצבע בולט רק לזו שרוצים להראות. ax.bar_label כותב את הערך על כל עמודה, וכך לא צריך לנחש מהציר. הסרת המסגרת העליונה והימנית מנקה רעש.

Good styling doesn't decorate, it helps reading. One colour for all bars, and a strong colour only for the one you want to show. ax.bar_label writes each bar's value on it, so nobody has to guess from the axis. Removing the top and right frame lines cuts noise.

style.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
pages = [412, 714, 518, 249, 600, 380]
best = pages.index(max(pages))
colors = ["#b8c2d6"] * len(pages)
colors[best] = "#2d5bd0"

fig, ax = plt.subplots(figsize=(6, 3))
bars = ax.bar(months, pages, color=colors)
ax.bar_label(bars, padding=2)
ax.spines[["top", "right"]].set_visible(False)
ax.set_title(f"Best month: {months[best]}")
fig.savefig("style.png", dpi=80, bbox_inches="tight")
פלטOutput
 
עמודות אפורות לכל חודש עם ערכים מעליהן, ופברואר (714) מודגש בכחול. כותרת: Best month: Feb.
style.png
אנלוגיה מהחייםReal-life analogy

להדגיש עמודה אחת זה כמו מרקר צהוב בסיכום: אם מסמנים הכול, שום דבר לא בולט.

Highlighting one bar is like a yellow marker on notes: highlight everything and nothing stands out.

טעות נפוצהCommon mistake

רשימת צבעים קצרה ממספר העמודות.

A colour list shorter than the number of bars.

style.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
bars = ax.bar(["a", "b", "c"], [1, 2, 3], color=["red", "blue"])
assert bars[2].get_facecolor() != bars[0].get_facecolor(), "the third bar silently reused the first colour"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/style.py", line 7, in <module>
    assert bars[2].get_facecolor() != bars[0].get_facecolor(), "the third bar silently reused the first colour"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: the third bar silently reused the first colour
בעברית פשוטה: In plain words: AssertionError: the third bar silently reused the first colour: matplotlib חוזר על הצבעים בלי להזהיר. בונים רשימה באורך המלא.AssertionError: the third bar silently reused the first colour: matplotlib cycles colours without warning. Build a full-length list.

05ישר מ-pandasStraight from pandas

ל-DataFrame ול-Series של pandas יש .plot() שמשתמש ב-matplotlib מאחורי הקלעים. משלבים עם groupby מהמפגש הקודם, ומקבלים גרף בשורה אחת. הפונקציה מחזירה Axes, אז אפשר להמשיך להוסיף כותרת ותוויות כרגיל.

pandas DataFrames and Series have a .plot() that uses matplotlib behind the scenes. Combine it with last session's groupby and you get a chart in one line. It returns an Axes, so you can keep adding a title and labels as usual.

from_pandas.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

import pandas as pd

df = pd.DataFrame({"month": ["Jan", "Feb", "Feb", "Mar", "Mar", "Apr"],
                   "pages": [412, 474, 240, 208, 310, 249]})
per_month = df.groupby("month", sort=False)["pages"].sum()
print(per_month)
ax = per_month.plot(kind="bar", color="#0e9f8e", figsize=(5, 3), rot=0)
ax.set_ylabel("Pages")
ax.figure.savefig("from_pandas.png", dpi=80, bbox_inches="tight")
פלטOutput
month
Jan    412
Feb    714
Mar    518
Apr    249
Name: pages, dtype: int64
עמודות ירוקות של עמודים לפי חודש מ-pandas: פברואר הגבוה ביותר.
from_pandas.png
אנלוגיה מהחייםReal-life analogy

plot של pandas הוא כמו כפתור "הוסף תרשים" באקסל: בוחרים נתונים ולוחצים, ואחר כך מסדרים את הפרטים.

pandas' plot is like Excel's "insert chart" button: pick the data and click, then tidy the details.

טעות נפוצהCommon mistake

כותבים kind שלא קיים.

Writing a kind that doesn't exist.

from_pandas.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

import pandas as pd
pd.Series([1, 2]).plot(kind="bars")
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/from_pandas.py", line 6, in <module>
    pd.Series([1, 2]).plot(kind="bars")
    ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/site-packages/pandas/plotting/_core.py", line 1118, in __call__
    raise ValueError(
        f"{kind} is not a valid plot kind Valid plot kinds: {self._all_kinds}"
    )
ValueError: bars is not a valid plot kind Valid plot kinds: ('line', 'bar', 'barh', 'kde', 'density', 'area', 'hist', 'box', 'pie', 'scatter', 'hexbin')
בעברית פשוטה: In plain words: ValueError: bars is not a valid plot kind: הסוגים הם למשל line, bar, barh, scatter, hist.ValueError: bars is not a valid plot kind: kinds are e.g. line, bar, barh, scatter, hist.

06כמה גרפים ושמירהSeveral charts and saving

plt.subplots(2, 1) יוצר שני Axes זה מעל זה. histogram (ax.hist) מראה איך ערכים מתפזרים. כששומרים, PNG מתאים למסמכים ו-SVG נשאר חד בכל גודל. ובלולאה שיוצרת הרבה גרפים, plt.close(fig) משחרר זיכרון.

plt.subplots(2, 1) makes two Axes one above the other. A histogram (ax.hist) shows how values spread. When saving, PNG suits documents and SVG stays sharp at any size. In a loop that makes many charts, plt.close(fig) frees memory.

many.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

pages = [412, 474, 240, 208, 310, 249, 96, 180, 520, 330, 290, 610]

fig, (top, bottom) = plt.subplots(2, 1, figsize=(6, 4.5))
top.plot(range(1, 13), pages, color="#8a3ffc")
top.set_title("Book length over the year")
bottom.hist(pages, bins=5, color="#f08c00", edgecolor="white")
bottom.set_title("How long are my books?")
fig.tight_layout()
fig.savefig("year.png", dpi=80)
plt.close(fig)
print(len(pages), "books")
פלטOutput
12 books
שני גרפים: למעלה קו של אורך הספרים לאורך השנה, למטה היסטוגרמה שמראה שרוב הספרים באורך 200 עד 400 עמודים.
year.png
אנלוגיה מהחייםReal-life analogy

histogram הוא כמו למיין תפוחים לסלים לפי גודל ולראות איזה סל הכי מלא.

A histogram is like sorting apples into baskets by size and seeing which basket is fullest.

טעות נפוצהCommon mistake

ניגשים ל-Axes השני כשנוצר רק אחד.

Accessing a second Axes when only one was created.

many.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 1)
axes[1].plot([1, 2])
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/many.py", line 6, in <module>
    axes[1].plot([1, 2])
    ~~~~^^^
TypeError: 'Axes' object is not subscriptable
בעברית פשוטה: In plain words: TypeError: 'Axes' object is not subscriptable: עם subplots(1, 1) מקבלים Axes אחד, לא רשימה. לשניים: plt.subplots(1, 2).TypeError: 'Axes' object is not subscriptable: subplots(1, 1) gives one Axes, not a list. For two: plt.subplots(1, 2).

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich