R: R ggplot2 المتقدم: تراكب الطبقات وأنظمة التجزئة
آخر تحديث: 2026-08-26
في الدرس السابق، تعرفنا على «السلسلة المكونة من ثلاثة أجزاء» لـ ggplot2:
ggplot() + aes() + geom_xxx()، والتي تتيح لنا إنشاء خمسة أنواع أساسية من الرسوم البيانية. في هذا الدرس، سننتقل إلى ggplot2 المتقدم — حيث سنتقن «تكديس الطبقات» و«نظام التجزئة» لإنشاء رسوم بيانية بأي درجة من التعقيد. وهنا تكمن الميزة الحقيقية لـ ggplot2.
بعد الانتهاء من هذا الدرس، ستتمكن من إنشاء: الرسوم البيانية المركبة متعددة الطبقات، والتقسيم التلقائي للأوجه، والتراكب الإحصائي، وتحويلات الإحداثيات، والتعليقات التوضيحية — حيث يغطي هذا الدرس 90% من الإمكانيات التي توفرها مكتبة ggplot2.
1. ما ستتعلمه
- استعراض بناء الجملة المكون من 7 طبقات في ggplot2
- تراكب الطبقات (أشكال هندسية متعددة + إحصائيات)
- facet_wrap() / facet_grid(): تصنيف العناصر
- طبقة الإحصائيات stat_summary()
- تحويلات الإحداثيات (coord_flip / coord_polar / coord_fixed)
- التعليق التوضيحي
- التطبيقات العملية للرسوم البيانية التجميعية المعقدة
2. قصة التحليل متعدد الأبعاد
(1) التحدي: كيف يمكنك تصميم عناصر بصرية لـ 4 مدن و4 أحياء و4 منتجات؟
يريد بوب عرض بيانات المبيعات لـ 4 مدن × 4 أرباع سنوية × 4 منتجات — فهل يمكن لمخطط واحد أن يستوعب هذه المعلومات ثلاثية الأبعاد؟
(2) الحل باستخدام ggplot2
# Use facet_wrap() to split "Products" into 4 small plots
ggplot(sales, aes(x = quarter, y = sales, color = city, group = city)) +
geom_line(linewidth = 1) +
geom_point(size = 3) +
facet_wrap(~ product) + # By Product Category
labs(title = "4 City × 4 Products Sales Trends")
# A Single Painting 4 Post a picture,Automatic Page Break!
سطر واحد facet_wrap() يحول صورة واحدة إلى 4. هذه هي قوة الاقتصاص.
3. استعراض بناء الجملة المكون من 7 طبقات في ggplot2
(1) هيكل مكون من 7 طبقات
graph TB
A[ggplot Plot] --> B[1. Data layer<br/>ggplot data]
A --> C[2. Aesthetic Mapping layer<br/>aes]
A --> D[3. Geometric Objects layer<br/>geom_xxx]
A --> E[4. Statistical Transformations layer<br/>stat_xxx]
A --> F[5. Coordinate System layer<br/>coord_xxx]
A --> G[6. Sub-section layer<br/>facet_xxx]
A --> H[7. Topic layer<br/>theme_xxx]
style A fill:#fff3cd
style B fill:#cce5ff
style C fill:#d4edda
style D fill:#f8d7da
style E fill:#e1d4ff
style F fill:#ffe1e1
style G fill:#e1ffe1
style H fill:#ffe1d4
(2) مثال على تراكب الطبقات
ggplot(df, aes(x, y)) + # Data + Aesthetics
geom_point() + # Geometric Layer 1:Scatter points
geom_smooth() + # Geometric Layer 2:Trendline
stat_summary() + # Statistical Layer
scale_y_log10() + # Coordinate Transformation
facet_wrap(~ group) + # Sub-section
theme_minimal() # Topic
+ وقم بترتيبها من الأسفل إلى الأعلى.
4. facet_wrap() / facet_grid() — تصنيف العناصر
(1) ما المقصود بـ«الوجه»؟
الوجه = تقسيم البيانات إلى عدة مخططات فرعية بناءً على متغير معين:
# Cone of Inadmissibility:1 Post a picture
ggplot(sales, aes(x, y)) + geom_point()
# After splitting:4 Zhang Xiaotu
ggplot(sales, aes(x, y)) + geom_point() + facet_wrap(~ category)
(2) facet_wrap(): التصفية الأبعاد الأحادية
# Split by city(4 subplots)
ggplot(sales_long, aes(x = quarter, y = sales, color = city, group = city)) +
geom_line() +
facet_wrap(~ city) +
labs(title = "Quarterly Sales by City")
# Control the Layout of Sub-Faces:nrow / ncol
facet_wrap(~ city, nrow = 2) # 2 row
facet_wrap(~ city, ncol = 4) # 4 col
(3) facet_grid(): التجزئة ثنائية الأبعاد
# Split by city(row) and product(col) Two-Dimensional Section
facet_grid(rows = vars(city), cols = vars(product))
# Abbreviation
facet_grid(city ~ product)
# Formula Syntax(Old Version)
facet_grid(. ~ category) # Press only category Split Plane
facet_grid(category ~ .) # Press only category Row-Column Plane
(4) المقارنة حسب الجانب
| القواعد النحوية | الاستخدام |
|---|---|
facet_wrap(~ var) |
التجزئة الأحادية البعد (فواصل الأسطر التلقائية) |
facet_grid(var ~ .) |
أحادي البعد (صف) |
facet_grid(. ~ var) |
أحادي البعد (عمودي) |
facet_grid(row ~ col) |
ثنائي الأبعاد (صفوف × أعمدة) |
(5) توسيع الأوجه
# Free Zoom(Independent coordinates for each subgraph)
facet_wrap(~ city, scales = "free") # Freedom x/y
facet_wrap(~ city, scales = "free_x") # Freedom Alone x
facet_wrap(~ city, scales = "free_y") # Freedom Alone y
# Add a tag
facet_wrap(~ city, labeller = label_both) # Display"city: Beijing"
# Control the number of subgraphs per row
facet_wrap(~ city, nrow = 2)
5. طبقة الإحصائيات stat_summary()
(1) الإحصاءات التلقائية
# Automatically Add Mean Points + Error bar
ggplot(df, aes(x = group, y = value)) +
geom_boxplot() +
stat_summary(fun = mean, geom = "point", color = "red", size = 3)
(2) الدوال الإحصائية الشائعة
| الوظيفة | الغرض |
|---|---|
mean |
المتوسط |
median |
الوسيط |
sd |
الانحراف المعياري |
sum |
المجموع |
function(x) mean(x) + sd(x) |
مخصص |
(3) التطبيق العملي: المتوسط + أشرطة الخطأ
ggplot(df, aes(x = group, y = value, color = group)) +
geom_point(alpha = 0.3) + # Raw Data
stat_summary(fun = mean, geom = "point", size = 4, color = "red") +
stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.2)
6. خط الاتجاه geom_smooth()
(1) الاستخدام الأساسي
# Auto-add LOESS Trendline
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth()
# Linear Regression
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm")
# Close Confidence Interval
geom_smooth(method = "lm", se = FALSE)
(2) التطبيق العملي
# Multiple lines by component
ggplot(sales_long, aes(x = quarter, y = sales, color = city, group = city)) +
geom_point() +
geom_line() +
geom_smooth(method = "lm", se = FALSE, linewidth = 0.5)
7. تحويل الإحداثيات
(1) coord_flip() انعكاس
# Horizontal Bar Chart
ggplot(df, aes(x = city, y = sales)) +
geom_col() +
coord_flip() # x/y Swap
(2) coord_polar() الإحداثيات القطبية
# Pie Chart
ggplot(df, aes(x = 1, y = sales, fill = city)) +
geom_col() +
coord_polar(theta = "y")
# Rose Illustration
ggplot(df, aes(x = city, y = sales, fill = city)) +
geom_col() +
coord_polar()
(3) coord_fixed() (مُقيَّس بشكل متناسب)
# Scatter Plot X/Y In the same proportion
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
coord_fixed(ratio = 1) # 1:1 Ratio
(4) تحويل محور الإحداثيات
# log Transformation
ggplot(df, aes(x, y)) + geom_point() + scale_y_log10()
# Square Root Transformation
ggplot(df, aes(x, y)) + geom_point() + scale_y_sqrt()
8. التعليقات والنص
(1) geom_text() / geom_label()
# Add labels next to the data points
ggplot(df, aes(x, y)) +
geom_point() +
geom_text(aes(label = name), vjust = -0.5)
# Add a circular label
ggplot(df, aes(x, y)) +
geom_point() +
geom_label(aes(label = name))
(2) annotate(): التعليق اليدوي
# Mark Key Points
ggplot(df, aes(x, y)) +
geom_point() +
annotate("text", x = 5, y = 8, label = "Key Points", color = "red") +
annotate("rect", xmin = 4, xmax = 6, ymin = 7, ymax = 9,
alpha = 0.2, fill = "yellow")
(3) سهم
library(ggrepel)
# "Auto-Skip" tag
ggplot(df, aes(x, y, label = name)) +
geom_point() +
geom_text_repel() # Non-overlapping tags
9. دمج صور متعددة
(1) حقيبة من قطع القماش المرقعة
# Installation
install.packages("patchwork")
library(patchwork)
# 4 Image Collage 1
(p1 + p2) / (p3 + p4) # 2 row 2 col
# Complex Layout
p1 + p2 + p3 + p4 + plot_layout(ncol = 2, heights = c(2, 1))
# Add a title
(p1 + p2) / (p3 + p4) + plot_annotation(title = "Comprehensive Analysis")
(2) حزمة cowplot
library(cowplot)
plot_grid(p1, p2, p3, p4, ncol = 2, labels = c("A", "B", "C", "D"))
10. مثال كامل: 4 مدن × 4 منتجات — التحليل متعدد الأبعاد
فيما يلي مثال على مسار عمل كامل يربط بين جميع الميزات المتقدمة التي تم تناولها في هذا الدرس.
▶ مثال: عرض مرئي شامل لبيانات المبيعات متعددة الأبعاد
# ============================================
# 4 City × 4 Products Multidimensional Sales Analysis
# Features:Sub-section + Trendline + Notes + Multi-Image Collage
# ============================================
library(ggplot2)
library(dplyr)
library(tidyr)
library(patchwork)
# 1. Prepare data
sales <- expand_grid(
city = c("Beijing", "Shanghai", "Guangzhou", "Shenzhen"),
quarter = c("Q1", "Q2", "Q3", "Q4"),
product = c("Cell Phone", "Computer", "Tablet", "Headphones")
) |>
mutate(sales = round(runif(64, 500, 3000)))
cat("=== Data Volume:", nrow(sales), "row ===\n")
print(head(sales, 5))
# 2. Plot 1:4 Overall Urban Trends(Basics)
p1 <- ggplot(sales, aes(x = quarter, y = sales, color = city, group = city)) +
geom_line(linewidth = 1) +
geom_point(size = 2) +
labs(title = "4 Overall Sales Trends by City", color = "City") +
theme_minimal() +
theme(legend.position = "bottom")
# 3. Plot 2:By City(facet_wrap)
p2 <- ggplot(sales, aes(x = quarter, y = sales, color = product, group = product)) +
geom_line(linewidth = 1) +
geom_point(size = 2) +
facet_wrap(~ city, nrow = 2) +
labs(title = "Product Sales by City", color = "Products") +
theme_minimal() +
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 45, hjust = 1))
# 4. Plot 3:By City(By Product Stack)
p3 <- ggplot(sales, aes(x = quarter, y = sales, fill = product)) +
geom_col(position = "stack") +
facet_wrap(~ city, nrow = 2) +
labs(title = "Product Bundle Sales by City", fill = "Products") +
scale_fill_brewer(palette = "Set2") +
theme_minimal() +
theme(legend.position = "bottom")
# 5. Plot 4:Trendline + Original Point
p4 <- ggplot(sales, aes(x = quarter, y = sales, color = city, group = city)) +
geom_point(alpha = 0.3) +
geom_smooth(method = "lm", se = TRUE) +
labs(title = "Linear Trendline + Confidence Interval") +
theme_minimal() +
theme(legend.position = "bottom")
# 6. Plot 5:Box-and-Whisker Plots
p5 <- ggplot(sales, aes(x = product, y = sales, fill = product)) +
geom_boxplot() +
labs(title = "Sales Breakdown by Product") +
theme_minimal() +
theme(legend.position = "none",
axis.text.x = element_text(angle = 45, hjust = 1))
# 7. Plot 6:Heat Map(geom_tile)
sales_summary <- sales |>
group_by(city, product) |>
summarise(total = sum(sales), .groups = "drop")
p6 <- ggplot(sales_summary, aes(x = city, y = product, fill = total)) +
geom_tile() +
geom_text(aes(label = total), color = "white") +
labs(title = "City × Products Total Sales Heat Map", fill = "Total Sales") +
scale_fill_gradient(low = "lightblue", high = "darkred") +
theme_minimal()
# 8. Multi-Image Collage(patchwork)
combined <- (p1 + p2) / (p3 + p4) / (p5 + p6) +
plot_annotation(
title = "4 City × 4 Products Comprehensive Sales Analysis",
subtitle = "Data Simulation | ggplot2 Photo Gallery"
)
print(combined)
# 9. Save as high resolution PNG
ggsave("multi_dimension_analysis.png", combined,
width = 16, height = 18, dpi = 300)
cat("\n=== The composite image has been saved:multi_dimension_analysis.png ===\n")
الناتج المتوقع: صورة كبيرة تتألف من 6 صور فرعية (مرتبة في شبكة 3×2 باستخدام طريقة «الترقيع»).
❓ أسئلة شائعة
facet_wrap وfacet_grid؟facet_wrap(~ var) تقسيم أحادي البعد (فواصل أسطر تلقائية)، facet_grid(rows ~ cols) تقسيم ثنائي البعد (صفوف وأعمدة ثابتة).geom_smooth؟method = "lm".theme(strip.background = element_blank()) (إزالة الخلفية) + theme(strip.text = element_text(color = "red")) (تغيير لون النص).p1 + p2 للترتيب جنبًا إلى جنب، وp1 / p2 للترتيب من أعلى إلى أسفل، و(p1 + p2) / (p3 + p4) للترتيب 2x2. استخدم plot_layout(ncol = 2) للتنسيقات المعقدة.ggrepel لتغليف geom_text_repel() / geom_label_repel()، وسوف يتجنب ذلك نقاط البيانات تلقائيًا.coord_flip تدوير بمقدار 90 درجة (مخطط أفقي)، coord_polar تحويل إلى إحداثيات قطبية (مخطط دائري/مخطط وردي).📖 ملخص
- صيغة ggplot2 ذات السبع طبقات: البيانات/الخصائص الجمالية/الهندسة/الإحصاءات/الإحداثيات/الأوجه/المواضيع
- استخدم
+لتركيب الطبقات، مع التكديس من الأسفل إلى الأعلى - الاتجاه:
facet_wrap(~ var)أحادي البعد /facet_grid(rows ~ cols)ثنائي البعد geom_smooth()إضافة خطوط الاتجاه تلقائيًا (LOESS/lm)stat_summary()إضافة طبقات إحصائية مثل المتوسط وأشرطة الخطأ- تحويلات الإحداثيات:
coord_flipانعكاس /coord_polarإحداثيات قطبية /scale_y_log10تحويل لوغاريتمي - ملاحظات:
geom_textتسمية البيانات /annotateالتعليق اليدوي /ggrepelالتجنب التلقائي - مجموعة الصور المتعددة: حزمة
patchwork(موصى بها) / حزمةcowplot - ggplot2 للمستخدمين المتقدمين = فن دمج الطبقات — إنشاء رسوم بيانية معقدة من طبقات بسيطة
📝 تمارين
-
تمرين أساسي: أنشئ إطار بيانات (30 صفًا، 4 أعمدة: x/y/group/category)، واستخدم
facet_wrap(~ group)لرسم مخطط مبعثر، وتحقق من تأثير التقطيع؛ ثم استخدمfacet_grid(group ~ category)لرسم شريحة ثنائية الأبعاد. -
تمرين أساسي: باستخدام
mtcars، ارسم مخططًا مبعثرًا لـwtمقابلmpg، وأضف خط اتجاه لـgeom_smooth(method = "lm")، وارسم منحنىً تربيعيًّا لـgeom_smooth(method = "lm", formula = y ~ poly(x, 2), color = "red")، ثم قارن بين النموذجين. -
تمرين أساسي: ارسم مخططًا شريطيًّا (مكونًا من 5 فئات)، واستخدم
coord_flip()لتدويره أفقيًّا، ثم استخدمcoord_polar()لتحويله إلى مخطط دائري، وقارن بين الاختلافات. -
تمرين متقدم: قم بإنشاء بيانات ثلاثية الأبعاد (x/y/group)، واستخدم ggplot2 لرسم ثلاثة مخططات مقطعية (
facet_wrap)، وأخيرًا استخدمpatchworkلدمجها في مخطط تجميعي أفقي بحجم 1×3 مع عنوان تلخيصي. -
التحدي: تحدي شامل — إنشاء مخطط مركب "بجودة النشر" واحد: ① باستخدام البيانات رباعية الأبعاد
mtcars(الوزن/ميل لكل جالون/عدد الأسطوانات/حصان) ② باستخدامfacet_wrap(~ cyl)للتقسيم حسب عدد الأسطوانات ③ أضف خط اتجاه LOESS ④ استخدمggrepelلإبراز المركبات الثلاث الأعلى والأدنى ⑤ استخدمpatchworkلإضافة مخطط صندوقي كمرجع ⑥ احفظه بتنسيق PNG عالي الدقة.