נבנה על ידיBuilt by Ariel Yohimovich
fig, ax = plt.subplots()fig, ax = plt.subplots()ax.plot(x, y) מצייר קוax.plot(x, y) draws a linefig.savefig(...) שומר, plt.show() מציגfig.savefig(...) saves, plt.show() displaysplt.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.)import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(["Jan", "Feb", "Mar"], [412, 714])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.ax.set_title, set_xlabel, set_ylabelax.set_title, set_xlabel, set_ylabellabel= לכל קו + ax.legend()label= per line + ax.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.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.import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(["Dune", "Emma"], [412, 474, 240])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.ax.bar_labelValues on the bars: ax.bar_labelax.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.df.plot(...) מחזיר Axesdf.plot(...) returns an Axes.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.import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
pd.Series([1, 2]).plot(kind="bars")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.plt.subplots(2, 1) = שני גרפיםplt.subplots(2, 1) = two chartssavefig("x.png", dpi=...), או .svg לחדותsavefig("x.png", dpi=...), or .svg for sharpnessplt.close(fig) בלולאותplt.close(fig) in loopsplt.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.import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 1)
axes[1].plot([1, 2])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 linefig.savefig(...) שומר, plt.show() מציגfig.savefig(...) saves, plt.show() displaysax.set_title, set_xlabel, set_ylabelax.set_title, set_xlabel, set_ylabellabel= לכל קו + ax.legend()label= per line + ax.legend()ax.bar_labelValues on the bars: ax.bar_labeldf.plot(...) מחזיר Axesdf.plot(...) returns an Axesfig, ax = plt.subplots()fig, ax = plt.subplots()ax.set_title, set_xlabel, set_ylabelax.set_title, set_xlabel, set_ylabeldf.plot(...) מחזיר Axesdf.plot(...) returns an Axesplt.subplots(2, 1) = שני גרפיםplt.subplots(2, 1) = two chartsנבנה על ידיBuilt by Ariel Yohimovich