R: R و ggplot2 للمبتدئين: دليل شامل لقواعد الرسوم البيانية

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

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

بعد الانتهاء من هذا الدرس، ستتمكن من إنشاء 5 أنواع أساسية من المخططات باستخدام ggplot2 وفهم المفهوم الأساسي لـ «التراكب».

1. ما ستتعلمه



2. قصة عن تصور البيانات

(1) المشكلة: واجهة R الأساسية قبيحة للغاية

استخدم بوب لغة R الأساسية لإنشاء رسم بياني يوضح اتجاهات المبيعات في أربع مدن:

R
plot(1:4, sales, type = "b")

ألقى المدير نظرة سريعة عليها وسأل: «هل يمكن إدراج هذه الصورة في التقرير؟»

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

R
library(ggplot2)

ggplot(sales_df, aes(x = quarter, y = sales, color = city, group = city)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  labs(title = "Q1-Q4 Sales Trends", x = "Quarter", y = "Sales") +
  theme_minimal()

4 أسطر من التعليمات البرمجية + رسوم بيانية بجودة النشر الافتراضية. هذه هي قوة ggplot2.



3. المفاهيم الأساسية لـ «قواعد الرسوم البيانية»

(1) ما هي «قواعد الرسوم البيانية»؟

100%
graph TB
    A[ggplot2 Charts] --> B[Data Data<br/>data]
    A --> C[Aesthetic Mapping Aesthetics<br/>aes]
    A --> D[Geometric Objects Geometries<br/>geom_xxx]
    A --> E[Statistical Transformations Statistics<br/>stat_xxx]
    A --> F[Coordinate System Coordinate<br/>coord_xxx]
    A --> G[Sub-section Facet<br/>facet_xxx]
    A --> H[Topic Theme<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

باختصار: تقسم مكتبة ggplot2 الرسم البياني إلى 7 طبقات، كل منها مستقلة وقابلة للاستبدال.

(2) الركائز الثلاث لـ ggplot2

الوظيفة الغرض مثال
ggplot() التهيئة (البيانات المحددة) ggplot(df)
aes() التخطيط الجمالي (المتغيرات → العناصر المرئية) aes(x, y, color)
geom_xxx() الأشكال الهندسية (الطبقات) geom_point()

مثال بسيط:

R
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point()


4. أول رسم بياني باستخدام ggplot2

(1) عملية الرسم في 5 خطوات

R
library(ggplot2)

# 1. Prepare data
df <- data.frame(
  x = 1:10,
  y = (1:10) ^ 2
)

# 2. Initialization(Data)
p <- ggplot(df, aes(x = x, y = y))

# 3. Add a Layer
p <- p + geom_point()

# 4. Add a tag
p <- p + labs(title = "Quadratic Curve", x = "X", y = "Y")

# 5. Add a topic
p <- p + theme_minimal()

# 6. Print
print(p)

أو استخدم + لتنفيذ كل ذلك دفعة واحدة:

R
ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  labs(title = "Quadratic Curve", x = "X", y = "Y") +
  theme_minimal()
💡 نصيحة: في ggplot2، استخدم + لربط الطبقات، على غرار استخدام |> لربط عمليات البيانات.

(2) الإخراج إلى ملف

R
# Save as PNG
ggsave("myplot.png", width = 8, height = 6, dpi = 300)

# Save as PDF(For a thesis)
ggsave("myplot.pdf", width = 8, height = 6)

# Custom Size
ggsave("myplot.png", width = 10, height = 8, units = "cm", dpi = 300)


5. رسم الخرائط الجمالي aes()

(1) التعيينات الشائعة

التعيين الدالة مثال
x، y إحداثيات X / Y aes(x = age, y = height)
color / colour اللون (الخارجي) aes(color = gender)
fill لون التعبئة (شريط/مساحة) aes(fill = region)
size حجم الخط aes(size = amount)
shape شكل النقطة aes(shape = category)
alpha الشفافية aes(alpha = weight)
linetype خطي aes(linetype = type)

(2) التطبيق العملي: الخرائط ثلاثية الأبعاد

R
# Color + Size + Shape 3 dimensions
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl), size = hp)) +
  geom_point(alpha = 0.7) +
  labs(title = "Vehicle Weight vs Fuel Consumption", color = "Number of cylinders", size = "Horsepower")

(3) ⚠️ داخل دالة aes() مقابل خارجها

R
# aes() Inside:Map to a variable(Each dot is a different color)
ggplot(df, aes(x, y, color = group)) + geom_point()
# → Different group Display different colors

# aes() Outside:Fixed value(All dots are the same color)
ggplot(df, aes(x, y)) + geom_point(color = "red")
# → All the dots are red
💡 نصيحة: سيتم تفسير color = "red" داخل aes() على أنه «العمود الأحمر» (إذا كانت البيانات تحتوي على عمود أحمر). يجب وضع الألوان الثابتة خارج aes().



6. 5 أشكال هندسية أساسية

(1) مخطط الانتشار باستخدام الدالة geom_point()

R
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
  geom_point(size = 3) +
  labs(title = "Vehicle Weight vs Fuel Consumption", x = "Weight", y = "Fuel Consumption")

(2) geom_line() الرسم البياني الخطي

R
df <- data.frame(
  x = 1:10,
  y = c(2, 4, 3, 5, 4, 6, 5, 7, 6, 8),
  group = "A"
)

ggplot(df, aes(x = x, y = y)) +
  geom_line(color = "blue", linewidth = 1) +
  geom_point(color = "blue", size = 3)

(3) geom_bar() الرسم البياني الشريطي

R
# Data
df <- data.frame(
  city = c("Beijing", "Shanghai", "Guangzhou", "Shenzhen"),
  sales = c(4800, 7000, 3900, 4500)
)

# Bar Chart
ggplot(df, aes(x = city, y = sales, fill = city)) +
  geom_bar(stat = "identity") +  # identity = Use y values
  labs(title = "Total Sales by City", x = "City", y = "Sales") +
  theme_minimal()
⚠️ ملاحظة: يستخدم geom_bar(stat = "identity") قيم المحور y الموجودة في البيانات؛ بينما يقوم geom_bar() بالعد بشكل افتراضي.

(4) geom_histogram() الرسم البياني التكراري

R
# 1000 A random number from a normal distribution
data <- data.frame(x = rnorm(1000, mean = 100, sd = 15))

ggplot(data, aes(x = x)) +
  geom_histogram(bins = 30, fill = "skyblue", color = "white") +
  labs(title = "Normal Distribution", x = "Value", y = "Frequency")

(5) geom_boxplot() الرسم البياني الصندوقي

R
# 4 Class Test Scores
scores <- data.frame(
  class = rep(c("1Cls", "2Cls", "3Cls", "4Cls"), each = 10),
  score = c(rnorm(10, 80, 8), rnorm(10, 75, 10),
            rnorm(10, 85, 7), rnorm(10, 70, 12))
)

ggplot(scores, aes(x = class, y = score, fill = class)) +
  geom_boxplot() +
  labs(title = "4 Class Grade Distribution", x = "Class", y = "Fractions")


7. العلامات والمواضيع

(1) علامة labs()

R
ggplot(df, aes(x, y)) +
  geom_point() +
  labs(
    title = "Main Title",
    subtitle = "Subtitle",
    caption = "Data Sources:xxx",
    x = "X Axis",
    y = "Y Axis",
    color = "Color Mapping",
    fill = "Fill Mapping"
  )

(2) السمة theme_xxx()

الموضوع النمط
theme_minimal() بسيط (الأكثر شيوعًا)
theme_bw() أبيض وأسود
theme_classic() الكلاسيكيات (الأكاديمية)
theme_void() فارغ
theme_light() ضوء
theme_dark() داكن
R
# Comparison 4 Topics
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
(p + theme_minimal())  # Default Recommendation
(p + theme_bw())
(p + theme_classic())
(p + theme_void())

(3) ضبط التفاصيل الدقيقة للسمة

R
p + theme(
  plot.title = element_text(size = 16, face = "bold"),
  axis.text = element_text(size = 10),
  legend.position = "bottom"  # Legend Location
)


8. الألوان والتعيينات

(1) ألوان منفصلة

R
# 1. Built-in Color Palette
p + scale_color_brewer(palette = "Set1")    # Classic
p + scale_color_brewer(palette = "Dark2")    # Dark
p + scale_color_brewer(palette = "Pastel1")  # Light-colored

# 2. Specify manually
p + scale_color_manual(values = c("red", "blue", "green"))

# 3. rainbow
p + scale_color_manual(values = rainbow(4))

(2) اللون المتواصل

R
# Gradient(For continuous variables)
p + scale_color_gradient(low = "blue", high = "red")
p + scale_color_viridis_c()   # viridis(Recommendations)
p + scale_color_distiller(palette = "RdYlBu")


9. مثال كامل: مبيعات متعددة الصور في 4 مدن

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

▶ مثال: 4 مدن، مجموعة من 5 صور

R 📖 للعرض فقط
# ============================================
# 4 City Sales 5 Image Gallery
# Features:Use ggplot2 to create 5 publication-quality charts
# ============================================

library(ggplot2)
library(dplyr)
library(tidyr)

# 1. Prepare data
sales_wide <- tibble(
  city = c("Beijing", "Shanghai", "Guangzhou", "Shenzhen"),
  Q1 = c(1000, 1500, 800, 1200),
  Q2 = c(1200, 1800, 900, 1400),
  Q3 = c(1100, 1700, 1000, 1300),
  Q4 = c(1500, 2000, 1200, 1600)
)

sales_long <- sales_wide |>
  pivot_longer(cols = -city, names_to = "quarter", values_to = "sales")

cat("=== Sales Data ===\n")
print(sales_long)

# 2. Plot 1:Linear Trend(By City)
p1 <- ggplot(sales_long, aes(x = quarter, y = sales, color = city, group = city)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  labs(title = "Q1-Q4 Sales Trends", x = "Quarter", y = "Sales", color = "City") +
  scale_color_brewer(palette = "Set1") +
  theme_minimal()

print(p1)

# 3. Plot 2:Total Sales Bar Chart
total_sales <- sales_wide |>
  mutate(total = Q1 + Q2 + Q3 + Q4) |>
  select(city, total)

p2 <- ggplot(total_sales, aes(x = reorder(city, total), y = total, fill = city)) +
  geom_bar(stat = "identity") +
  coord_flip() +  # Sideways
  labs(title = "Total Sales by City", x = "City", y = "Total Sales") +
  theme_minimal() +
  theme(legend.position = "none")

print(p2)

# 4. Plot 3:Pie Chart of Percentage Distributions(geom_bar + coord_polar)
p3 <- ggplot(total_sales, aes(x = "", y = total, fill = city)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar(theta = "y") +  # Polar Coordinates(Pie Chart)
  labs(title = "Share of Sales") +
  theme_void() +
  scale_fill_brewer(palette = "Set2")

print(p3)

# 5. Plot 4:Histogram(All Sales Data)
p4 <- ggplot(sales_long, aes(x = sales, fill = city)) +
  geom_histogram(bins = 10, alpha = 0.7, position = "identity") +
  labs(title = "Sales Distribution", x = "Sales", y = "Frequency") +
  scale_fill_brewer(palette = "Set1") +
  theme_minimal()

print(p4)

# 6. Plot 5:Box-and-Whisker Plot(By City)
p5 <- ggplot(sales_long, aes(x = city, y = sales, fill = city)) +
  geom_boxplot() +
  labs(title = "Sales Distribution by City", x = "City", y = "Sales") +
  theme_minimal() +
  theme(legend.position = "none")

print(p5)

# 7. Save All Images
ggsave("01_trend.png", p1, width = 8, height = 6, dpi = 300)
ggsave("02_total.png", p2, width = 8, height = 6, dpi = 300)
ggsave("03_pie.png", p3, width = 8, height = 6, dpi = 300)
ggsave("04_hist.png", p4, width = 8, height = 6, dpi = 300)
ggsave("05_box.png", p5, width = 8, height = 6, dpi = 300)

cat("\n=== 5 The image has been saved ===\n")
cat("  01_trend.png - Linear Trend\n")
cat("  02_total.png - Bar Chart Comparison\n")
cat("  03_pie.png - Pie Chart of Percentage Distributions\n")
cat("  04_hist.png - Histogram\n")
cat("  05_box.png - Urban Box Lines\n")
61 سطر من الكود المنطقي (تجاوز الحد 40, للعرض فقط)

الناتج المتوقع: 5 رسوم بيانية بجودة النشر (القالب الافتراضي «theme_minimal» جذاب بما فيه الكفاية بالفعل).



❓ أسئلة شائعة

س ما الفرق بين geom_bar() وgeom_col()؟
ج يستخدم geom_bar(stat = "identity") قيمة y؛ أما geom_col() فهو «تسهيل نحوي» لها (أكثر إيجازًا). يتم العد في geom_bar() بشكل افتراضي (لا حاجة إلى y).
س كيف يمكنني إضافة تعليقات؟
ج استخدم geom_text() / geom_label():
R
ggplot(df, aes(x, y)) + geom_point() +
  geom_text(aes(label = name), vjust = -0.5)  # Add labels above the data points
س كيف يمكنني إزالة التوضيح؟
ج theme(legend.position = "none").
س كيف يمكنني حفظ الصور عالية الدقة؟
ج ggsave("plot.png", dpi = 300, width = 8, height = 6)، 300 نقطة في البوصة هي المعيار القياسي للطباعة.

📖 ملخص


📝 تمارين

  1. تمرين أساسي: أنشئ إطار بيانات (10 صفوف، وعمودين من قيم x و y)، واستخدم ggplot + geom_point + labs + theme_minimal لرسم مخطط مبعثر، وتحقق من الفرق بين color = "red" (الداخل) وcolor = "red" (الخارج) في aes().

  2. تمرين أساسي: أنشئ مخططًا مبعثرًا باستخدام مجموعة البيانات mtcars (wt مقابل mpg)، وقم بتلوين النقاط وفقًا لـ cyl (color = factor(cyl))، وأضف عنوانًا وموضوعًا باستخدام labs().

  3. تمرين أساسي: أنشئ إطار بيانات (5 مدن + أرقام المبيعات)، واستخدم geom_col() لرسم مخطط شريطي، وقم بفرز البيانات باستخدام reorder(city, sales)، وتحقق من نتائج الفرز.

  4. تمرين متقدم: قم بمحاكاة درجات الفصل 4 الذي يضم 30 طالبًا، واستخدم geom_boxplot() لرسم مخطط توزيع الدرجات للفصل 4، وأضف fill = class لتحديد لون التعبئة وtheme_minimal() لتحديد السمة.

  5. التحدي: استخدم mtcars لإنشاء 6 رسوم بيانية (بالجمع بين نمط par(mfrow) وggplot2): ① مخطط مبعثر لـ wt مقابل mpg ② رسم بياني تكراري لتوزيع wt ③ مخطط صندوقي لـ mpg ④ wt مقابل mpg حسب عدد الأسطوانات ⑤ مخطط مبعثر مع خريطة ألوان ⑥ تخصيص كامل للمظهر. احفظ الرسوم البيانية الستة بصيغة PDF.

Web-Tutorial.com

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

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

100%