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

חזרה למפגשBack
PythonPython

גרפים עם matplotlibCharts with matplotlib

מפגש 25: קו, עמודות, עוגה ושמירה לקובץ.Session 25: Line, bar, pie and saving to a file.

מה נעשה היוםToday's plan

  • גרףChart
  • תוויותLabels
  • סוגיםTypes
  • עיצובStyle
  • pandaspandas
  • שמירהSaving
נושאTopic 1

גרףChart

גרף ראשוןYour first chart

  • fig, ax = plt.subplots()fig, ax = plt.subplots()
  • ax.plot(x, y) מצייר קוax.plot(x, y) draws a line
  • fig.savefig(...) שומר, plt.show() מציגfig.savefig(...) saves, plt.show() displays

אנלוגיה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

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
ValueError: x and y must have same first dimension, but have shapes (3,) and (2,)
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.
נושאTopic 2

תוויותLabels

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

  • ax.set_title, set_xlabel, set_ylabelax.set_title, set_xlabel, set_ylabel
  • label= לכל קו + ax.legend()label= per line + ax.legend()
  • גרף בלי תוויות הוא חידהA chart without labels is a riddle

אנלוגיהAnalogy

מקרא הוא כמו מפתח במפה: בלעדיו, קו כחול וקו כתום הם סתם קווים.A legend is like a map key: without it, a blue line and an orange line are just lines.
נושאTopic 3

סוגיםTypes

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

  • שינוי לאורך זמן → קוChange over time → line
  • השוואה בין קטגוריות → עמודותComparing categories → bars
  • קשר בין שני מספרים → פיזורRelation between two numbers → scatter

אנלוגיה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

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
ValueError: shape mismatch: objects cannot be broadcast to a single shape.  Mismatch is between 'x' with shape (2,) and 'height' with shape (3,).
ValueError: shape mismatch: לכל עמודה צריך גובה אחד. בודקים ששתי הרשימות באותו אורך.ValueError: shape mismatch: every bar needs one height. Check both lists have the same length.
נושאTopic 4

עיצובStyle

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

  • צבע אחד, והדגשה רק למה שחשובOne colour, highlight only what matters
  • ערכים על העמודות: ax.bar_labelValues on the bars: ax.bar_label
  • להסיר מסגרות מיותרותRemove unneeded frames

אנלוגיהAnalogy

להדגיש עמודה אחת זה כמו מרקר צהוב בסיכום: אם מסמנים הכול, שום דבר לא בולט.Highlighting one bar is like a yellow marker on notes: highlight everything and nothing stands out.
נושאTopic 5

pandaspandas

ישר מ-pandasStraight from pandas

  • df.plot(...) מחזיר Axesdf.plot(...) returns an Axes
  • groupby → plot בשורה אחתgroupby → plot in one line
  • ממשיכים לעצב עם axKeep styling with ax

אנלוגיהAnalogy

plot של pandas הוא כמו כפתור "הוסף תרשים" באקסל: בוחרים נתונים ולוחצים, ואחר כך מסדרים את הפרטים.pandas' plot is like Excel's "insert chart" button: pick the data and click, then tidy the details.

טעות נפוצהCommon mistake

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
ValueError: bars is not a valid plot kind Valid plot kinds: ('line', 'bar', 'barh', 'kde', 'density', 'area', 'hist', 'box', 'pie', 'scatter', 'hexbin')
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.
נושאTopic 6

שמירהSaving

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

  • plt.subplots(2, 1) = שני גרפיםplt.subplots(2, 1) = two charts
  • savefig("x.png", dpi=...), או .svg לחדותsavefig("x.png", dpi=...), or .svg for sharpness
  • plt.close(fig) בלולאותplt.close(fig) in loops

אנלוגיהAnalogy

histogram הוא כמו למיין תפוחים לסלים לפי גודל ולראות איזה סל הכי מלא.A histogram is like sorting apples into baskets by size and seeing which basket is fullest.

טעות נפוצהCommon mistake

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
TypeError: 'Axes' object is not subscriptable
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).

fig, ax = plt.subplots()fig, ax = plt.subplots()

ax.plot(x, y) מצייר קוax.plot(x, y) draws a line

fig.savefig(...) שומר, plt.show() מציגfig.savefig(...) saves, plt.show() displays

ax.set_title, set_xlabel, set_ylabelax.set_title, set_xlabel, set_ylabel

label= לכל קו + ax.legend()label= per line + ax.legend()

גרף בלי תוויות הוא חידהA chart without labels is a riddle

שינוי לאורך זמן → קוChange over time → line

השוואה בין קטגוריות → עמודותComparing categories → bars

קשר בין שני מספרים → פיזורRelation between two numbers → scatter

צבע אחד, והדגשה רק למה שחשובOne colour, highlight only what matters

ערכים על העמודות: ax.bar_labelValues on the bars: ax.bar_label

להסיר מסגרות מיותרותRemove unneeded frames

df.plot(...) מחזיר Axesdf.plot(...) returns an Axes

groupby → plot בשורה אחתgroupby → plot in one line

מה למדנוWhat we learned

  • fig, ax = plt.subplots()fig, ax = plt.subplots()
  • ax.set_title, set_xlabel, set_ylabelax.set_title, set_xlabel, set_ylabel
  • שינוי לאורך זמן → קוChange over time → line
  • צבע אחד, והדגשה רק למה שחשובOne colour, highlight only what matters
  • df.plot(...) מחזיר Axesdf.plot(...) returns an Axes
  • plt.subplots(2, 1) = שני גרפיםplt.subplots(2, 1) = two charts

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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