נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • fig, ax = plt.subplots()fig, ax = plt.subplots()
  • ax.plot(x, y) מצייר קוax.plot(x, y) draws a line
  • ax.set_title, set_xlabel, set_ylabelax.set_title, set_xlabel, set_ylabel
  • label= לכל קו + ax.legend()label= per line + ax.legend()
  • שינוי לאורך זמן → קוChange over time → line
  • השוואה בין קטגוריות → עמודותComparing categories → bars
  • צבע אחד, והדגשה רק למה שחשובOne colour, highlight only what matters
  • ערכים על העמודות: ax.bar_labelValues on the bars: ax.bar_label
  • df.plot(...) מחזיר Axesdf.plot(...) returns an Axes

מונחיםTerms

  • matplotlibmatplotlib: הספרייה הוותיקה והנפוצה לציור גרפים בפייתון. import matplotlib.pyplot as plt.Python's long-standing, most common charting library. import matplotlib.pyplot as plt.
  • Figure ו-AxesFigure and Axes: Figure הוא הדף כולו; Axes הוא גרף אחד בתוכו, עם הצירים שלו. fig, ax = plt.subplots().The Figure is the whole page; an Axes is one chart inside it, with its own axes. fig, ax = plt.subplots().
  • מקראlegend: התיבה שמסבירה איזה צבע או קו שייך לאיזו סדרה.The box explaining which colour or line belongs to which series.
  • savefigsavefig: שמירת הגרף לקובץ תמונה (PNG, SVG, PDF). fig.savefig("chart.png").Saving the chart to an image file (PNG, SVG, PDF). fig.savefig("chart.png").

Cheatsheet

גרףChart
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
pages = [412, 714, 518, 249, 600, 380]
תוויותLabels
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]
סוגיםTypes
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

authors = ["Austen", "Dahl", "Herbert", "Tolkien"]
pages = [723, 448, 412, 310]
עיצובStyle
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))
pandaspandas
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

import pandas as pd

df = pd.DataFrame({"month": ["Jan", "Feb", "Feb", "Mar", "Mar", "Apr"],
שמירהSaving
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))

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
ValueErrorשתי רשימות באורך שונה.Two lists of different lengths.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.
UserWarningקוראים ל-ax.legend() בלי שנתתם label לאף קו.Calling ax.legend() without giving any line a label.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.
ValueErrorמספר שמות שונה ממספר הגבהים.A different number of names and heights.ValueError: shape mismatch: לכל עמודה צריך גובה אחד. בודקים ששתי הרשימות באותו אורך.ValueError: shape mismatch: every bar needs one height. Check both lists have the same length.
AssertionErrorרשימת צבעים קצרה ממספר העמודות.A colour list shorter than the number of bars.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.
ValueErrorכותבים kind שלא קיים.Writing a kind that doesn't exist.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.
TypeErrorניגשים ל-Axes השני כשנוצר רק אחד.Accessing a second Axes when only one was created.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).

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