R: R ggplot2 المتقدم: تراكب الطبقات وأنظمة التجزئة

آخر تحديث: 2026-08-26

في الدرس السابق، تعرفنا على «السلسلة المكونة من ثلاثة أجزاء» لـ ggplot2: ggplot() + aes() + geom_xxx()، والتي تتيح لنا إنشاء خمسة أنواع أساسية من الرسوم البيانية. في هذا الدرس، سننتقل إلى ggplot2 المتقدم — حيث سنتقن «تكديس الطبقات» و«نظام التجزئة» لإنشاء رسوم بيانية بأي درجة من التعقيد. وهنا تكمن الميزة الحقيقية لـ ggplot2.

بعد الانتهاء من هذا الدرس، ستتمكن من إنشاء: الرسوم البيانية المركبة متعددة الطبقات، والتقسيم التلقائي للأوجه، والتراكب الإحصائي، وتحويلات الإحداثيات، والتعليقات التوضيحية — حيث يغطي هذا الدرس 90% من الإمكانيات التي توفرها مكتبة ggplot2.

1. ما ستتعلمه



2. قصة التحليل متعدد الأبعاد

(1) التحدي: كيف يمكنك تصميم عناصر بصرية لـ 4 مدن و4 أحياء و4 منتجات؟

يريد بوب عرض بيانات المبيعات لـ 4 مدن × 4 أرباع سنوية × 4 منتجات — فهل يمكن لمخطط واحد أن يستوعب هذه المعلومات ثلاثية الأبعاد؟

(2) الحل باستخدام ggplot2

R
# 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 طبقات

100%
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) مثال على تراكب الطبقات

R
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) ما المقصود بـ«الوجه»؟

الوجه = تقسيم البيانات إلى عدة مخططات فرعية بناءً على متغير معين:

R
# 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(): التصفية الأبعاد الأحادية

R
# 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")
R
# 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(): التجزئة ثنائية الأبعاد

R
# 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) توسيع الأوجه

R
# 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) الإحصاءات التلقائية

R
# 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) التطبيق العملي: المتوسط + أشرطة الخطأ

R
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) الاستخدام الأساسي

R
# 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) التطبيق العملي

R
# 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() انعكاس

R
# Horizontal Bar Chart
ggplot(df, aes(x = city, y = sales)) +
  geom_col() +
  coord_flip()  # x/y Swap

(2) coord_polar() الإحداثيات القطبية

R
# 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() (مُقيَّس بشكل متناسب)

R
# Scatter Plot X/Y In the same proportion
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  coord_fixed(ratio = 1)  # 1:1 Ratio

(4) تحويل محور الإحداثيات

R
# 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()

R
# 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(): التعليق اليدوي

R
# 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) سهم

R
library(ggrepel)

# "Auto-Skip" tag
ggplot(df, aes(x, y, label = name)) +
  geom_point() +
  geom_text_repel()  # Non-overlapping tags


9. دمج صور متعددة

(1) حقيبة من قطع القماش المرقعة

R
# 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

R
library(cowplot)
plot_grid(p1, p2, p3, p4, ncol = 2, labels = c("A", "B", "C", "D"))


10. مثال كامل: 4 مدن × 4 منتجات — التحليل متعدد الأبعاد

فيما يلي مثال على مسار عمل كامل يربط بين جميع الميزات المتقدمة التي تم تناولها في هذا الدرس.

▶ مثال: عرض مرئي شامل لبيانات المبيعات متعددة الأبعاد

R 📖 للعرض فقط
# ============================================
# 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")
63 سطر من الكود المنطقي (تجاوز الحد 40, للعرض فقط)

الناتج المتوقع: صورة كبيرة تتألف من 6 صور فرعية (مرتبة في شبكة 3×2 باستخدام طريقة «الترقيع»).



❓ أسئلة شائعة

س ما الفرق بين facet_wrap وfacet_grid؟
ج facet_wrap(~ var) تقسيم أحادي البعد (فواصل أسطر تلقائية)، facet_grid(rows ~ cols) تقسيم ثنائي البعد (صفوف وأعمدة ثابتة).
س ما هو الإعداد الافتراضي لـ geom_smooth؟
ج الإعداد الافتراضي هو التسوية باستخدام طريقة LOESS (n < 1000) أو طريقة GAM (n ≥ 1000). لاستخدام الانحدار الخطي، أضف method = "lm".
س كيف يمكنني إزالة الخلفية من تسميات الصفحات؟
ج theme(strip.background = element_blank()) (إزالة الخلفية) + theme(strip.text = element_text(color = "red")) (تغيير لون النص).
س كيف أستخدم "patchwork"؟
ج استخدم p1 + p2 للترتيب جنبًا إلى جنب، وp1 / p2 للترتيب من أعلى إلى أسفل، و(p1 + p2) / (p3 + p4) للترتيب 2x2. استخدم plot_layout(ncol = 2) للتنسيقات المعقدة.
س كيف يمكنني إضافة تسميات نصية دون أن تتداخل مع بعضها؟
ج استخدم ggrepel لتغليف geom_text_repel() / geom_label_repel()، وسوف يتجنب ذلك نقاط البيانات تلقائيًا.
س ما الفرق بين coord_polar و coord_flip؟
ج coord_flip تدوير بمقدار 90 درجة (مخطط أفقي)، coord_polar تحويل إلى إحداثيات قطبية (مخطط دائري/مخطط وردي).

📖 ملخص


📝 تمارين

  1. تمرين أساسي: أنشئ إطار بيانات (30 صفًا، 4 أعمدة: x/y/group/category)، واستخدم facet_wrap(~ group) لرسم مخطط مبعثر، وتحقق من تأثير التقطيع؛ ثم استخدم facet_grid(group ~ category) لرسم شريحة ثنائية الأبعاد.

  2. تمرين أساسي: باستخدام mtcars، ارسم مخططًا مبعثرًا لـ wt مقابل mpg، وأضف خط اتجاه لـ geom_smooth(method = "lm")، وارسم منحنىً تربيعيًّا لـ geom_smooth(method = "lm", formula = y ~ poly(x, 2), color = "red")، ثم قارن بين النموذجين.

  3. تمرين أساسي: ارسم مخططًا شريطيًّا (مكونًا من 5 فئات)، واستخدم coord_flip() لتدويره أفقيًّا، ثم استخدم coord_polar() لتحويله إلى مخطط دائري، وقارن بين الاختلافات.

  4. تمرين متقدم: قم بإنشاء بيانات ثلاثية الأبعاد (x/y/group)، واستخدم ggplot2 لرسم ثلاثة مخططات مقطعية (facet_wrap)، وأخيرًا استخدم patchwork لدمجها في مخطط تجميعي أفقي بحجم 1×3 مع عنوان تلخيصي.

  5. التحدي: تحدي شامل — إنشاء مخطط مركب "بجودة النشر" واحد: ① باستخدام البيانات رباعية الأبعاد mtcars (الوزن/ميل لكل جالون/عدد الأسطوانات/حصان) ② باستخدام facet_wrap(~ cyl) للتقسيم حسب عدد الأسطوانات ③ أضف خط اتجاه LOESS ④ استخدم ggrepel لإبراز المركبات الثلاث الأعلى والأدنى ⑤ استخدم patchwork لإضافة مخطط صندوقي كمرجع ⑥ احفظه بتنسيق PNG عالي الدقة.

Web-Tutorial.com

فريق Web-Tutorial التقني

منصة دروس برمجية يديرها عدة مطورين. كل درس يتم كتابته ومراجعته بواسطة مطورين متخصصين في المجال. نعمل على ضمان دقة وموثوقية المحتوى — إذا لاحظت أي مشكلة، فيرجى إخبارنا.

100%