Plotly
Plotly بترسم charts تفاعلية: hover عشان الأرقام، واسحب عشان تعمل zoom، ودبل كليك يرجّعها، وكليك على الـ legend يخبّي series.
لو عارف Seaborn و Matplotlib، فإنت عارف أغلبها:
px زي Seaborn، و go زي الـ object-oriented بتاع Matplotlib.
الدرس كله على داتا Airbnb في نيويورك، والرسومات اللي هنا Plotly حقيقية: جرّب الـ hover والـ zoom.
1الفكرة
كل figure في Plotly عبارة عن حاجتين: data (list من الـ traces) و layout (كل حاجة تانية).
print(fig) بيوريك الـ dictionary ده بالظبط.
| Matplotlib | Plotly |
|---|---|
| Figure | go.Figure |
| Axes | layout.xaxis / yaxis |
| الـ artist بتاع ax.plot() | trace (go.Scatter، go.Bar…) |
| ax.set_title() وأخواتها | fig.update_layout() |
| plt.show() | fig.show() |
الـ median لسعر الليلة في كل borough. شغّل الـ updates واحدة واحدة:
2Plotly Express (زي Seaborn)
call واحد على DataFrame. الأسامي بس اللي بتتغيّر:
| Seaborn | px |
|---|---|
| hue | color |
| style | symbol / line_dash |
| col / row | facet_col / facet_row |
| col_wrap | facet_col_wrap |
| palette | color_discrete_sequence / color_continuous_scale |
| order | category_orders |
px.scatter(sample, x="distance_km", y="price", color="room_type", size="number_of_reviews", hover_data=["neighbourhood"], trendline="ols") # trendline needs statsmodels px.line(long, x="last_review", y="listings", color="borough") # px likes LONG data px.line(wide, x="last_review", y=["Manhattan", "Brooklyn", "Queens"]) # wide works too px.histogram(sample, y="price", nbins=50, marginal="box") # aggregates for you px.box(sample, x="borough", y="price", color="room_type", log_y=True) px.ecdf(sample, x="price", color="room_type") px.imshow(df[cols].corr(method="spearman"), text_auto=".2f", zmin=-1, zmax=1) # fix -1..1 or the colours lie px.scatter_matrix(sample, dimensions=["price", "distance_km", "number_of_reviews"]) px.pie(hoods, names="borough", values="listings", hole=0.4) # pie DOES sum per name
⚠️ الـ px.bar مبيجمّعش
sns.barplot بيحسب المتوسط لوحده. px.bar بيرسم اللي بيوصله: ادّيله سطور خام، وهيرصّ حتة رفيعة لكل listing، فكل bar يبقى مجموع الأسعار.
Facets
fig = px.scatter(sample, x="distance_km", y="price", facet_col="borough", facet_row="room_type", log_y=True) fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1])) # "borough=Bronx" -> "Bronx"
3graph_objects (زي Matplotlib OO)
trace واحد = call واحد لـ ax.plot(). والـ mode: lines · markers · lines+markers · text.
fig = go.Figure() fig.add_trace(go.Bar(x=stats.index, y=stats["median"], name="median")) # mix trace types fig.add_trace(go.Scatter(x=stats.index, y=stats["mean"], name="mean", mode="lines+markers")) go.Figure([ # fill between (= ax.fill_between) go.Scatter(x=band.index, y=band[0.75], line_width=0, showlegend=False), go.Scatter(x=band.index, y=band[0.25], fill="tonexty", line_width=0, name="Q1-Q3"), go.Scatter(x=band.index, y=band[0.5], name="median"), ])
في كل borough المتوسط فوق الـ median: شوية listings غالية بيشدّوه لفوق (الأسعار skewed لليمين).
4الشكل: الـ update_*
الـ magic underscore: xaxis_title="X" هي نفسها xaxis=dict(title="X").
fig.update_layout(title=dict(text="...", x=0.5), xaxis_title="...", template="simple_white", legend=dict(orientation="h", y=-0.2)) # everything outside the traces fig.update_xaxes(range=[0, 30], showgrid=False) # = set_xlim fig.update_yaxes(tickprefix="$", type="log") # = set_yscale("log") fig.update_traces(marker=dict(size=10, opacity=0.7)) # every trace fig.update_traces(line_width=4, selector=dict(name="Manhattan")) # one trace fig.add_hline(y=1000, line_dash="dot", annotation_text="1,000 listings") # = axhline fig.add_vrect(x0="2018-11-01", x1="2018-12-31", fillcolor="red", opacity=0.15) # = axvspan fig.add_annotation(x=..., y=..., text="Peak", showarrow=True) # = annotate
والـ default للكل: pio.templates.default = "simple_white"
5Subplots (زي plt.subplots)
fig = make_subplots(rows=2, cols=2, specs=[[{"colspan": 2}, None], # a panel spanning 2 columns [{}, {}]], subplot_titles=("Wide", "Left", "Right")) fig.add_trace(go.Scatter(x=wide["last_review"], y=wide["Manhattan"]), row=1, col=1) fig.add_trace(go.Histogram(x=sample["price"]), row=2, col=1) fig.add_trace(go.Box(y=sample["price"]), row=2, col=2)
الفرق عن Matplotlib: بتحدد الـ panel لكل trace بـ row= و col=، بدل ما تمسك Axes. و secondary_y=True لمحور y تاني.
6الـ Hover
الـ hover الافتراضي بيكرر x و y، اللي القارئ شايفهم أصلًا. خلّيه يجاوب السؤال اللي بعده: الـ listing دي إيه؟ حط الماوس على النقط:
ولما يبقى فيه كذا خط على نفس الـ x: fig.update_layout(hovermode="x unified") = tooltip واحد للكل.
7Controls جوه الرسمة
الـ controls دي جوه الـ figure نفسها، وشغالة كمان في الـ HTML المحفوظ. للـ widgets اللي بتتحكم في صفحة كاملة، استنى درس Streamlit.
Animation
frame لكل سنة من آخر review: كل فقاعة neighbourhood، من الـ listings اللي آخر review ليها في السنة دي. حرّك السنة، وجرّب من غير ما تقفل المحاور:
px.scatter(yearly, x="distance", y="price", size="listings", color="borough", hover_name="neighbourhood", animation_frame="year", animation_group="neighbourhood", log_y=True, range_x=[0, 36], range_y=[20, 1000]) # ALWAYS fix the ranges
Range slider و dropdown
fig.update_xaxes(rangeslider_visible=True, rangeselector=dict(buttons=[ dict(count=3, label="3m", step="month", stepmode="backward"), dict(step="all")])) fig.update_layout(updatemenus=[dict(buttons=[ dict(label="Linear", method="relayout", args=[{"yaxis.type": "linear"}]), dict(label="Log", method="relayout", args=[{"yaxis.type": "log"}])])])
عدد الـ listings حسب شهر آخر review ليها، من 2018. اسحب أطراف الـ slider تحت، أو اختار Linear / Log.
8خرايط، و 3D، و hierarchy، و finance
خريطة من غير خريطة، و range_color
الـ longitude والـ latitude كـ x و y، واللون السعر. شيل الـ range_color وشوف إيه اللي بيحصل:
9الحفظ
fig.write_html() بيحفظ الرسمة كصفحة ويب: اللي يفتحها بياخد الرسمة التفاعلية كاملة في المتصفح، من غير Python.
fig.write_html("output/plot.html") # plotly.js inside: 4.6 MB, works offline fig.write_html("output/plot_cdn.html", include_plotlyjs="cdn") # plotly.js from the internet: 0.1 MB fig.write_image("plot.png", scale=3) # static: needs kaleido
الـ default (True)
plotly.js جوه الملف. كبير، بس بيفتح في أي حتة حتى من غير نت: لابتوب، موبايل، attachment في إيميل.
لما تبعته لحد.
"cdn"
الملف فيه الداتا بس وسطر "نزّل plotly.js من النت". صغير، بس من غير نت الصفحة فاضية.
لما تحطه على موقع.
10مطبات
✗ مفيش global state
مفيش plt.gca(): امسك الـ fig دايمًا.
✗ px.bar مبيجمّعش
groupby الأول، أو px.histogram بـ histfunc.
✗ أرقام كـ strings
المحور بيبقى categorical. اجبره: update_xaxes(type="category") أو حوّل النوع.
✗ كل سطر بيسافر مع الرسمة
48,000 نقطة بطيئة وتقيلة. جمّع أو خد sample قبل ما ترسم، أو render_mode="webgl" للداتا الكبيرة.
✗ ترتيب الـ traces
هو ترتيب الرسم وترتيب الـ legend.
✗ الرسمة فاضية في Jupyter؟
ظبّط pio.renderers.default: "notebook"، "vscode"، "browser".