R: R و ggplot2 للمبتدئين: دليل شامل لقواعد الرسوم البيانية
آخر تحديث: 2026-08-26
في الدرس السابق، تناولنا أساسيات الرسم البياني في لغة R — وهي طريقة سريعة لكنها غير جذابة. في هذا الدرس، سنتعمق في «السلاح السري» الحقيقي للغة R — ggplot2. صممها هادلي ويكهام، وتجعل صيغة «قواعد الرسوم البيانية» الخاصة بها عملية الرسم البياني سهلة مثل «البناء بالقطع المربعة»، وتنتج عروضًا مرئية بجودة النشر بشكل افتراضي، وتُستخدم في 90% من الأوراق البحثية الأكاديمية التي تستخدم لغة R.
بعد الانتهاء من هذا الدرس، ستتمكن من إنشاء 5 أنواع أساسية من المخططات باستخدام ggplot2 وفهم المفهوم الأساسي لـ «التراكب».
1. ما ستتعلمه
- ggplot2 الأساسي: قواعد بناء الجمل في «قواعد الرسوم البيانية»
- الثلاثي «ggplot() + aes() + geom_xxx()»
- 5 أشكال هندسية أساسية: النقطة / الخط / الشريط / الرسم البياني التكراري / الرسم البياني الصندوقي
- التخطيط الجمالي aes(x, y, اللون, الحجم, الشكل)
- العلامة labs() + السمة theme_minimal()
- الاختلافات الرئيسية بين ggplot2 و R الأساسي
2. قصة عن تصور البيانات
(1) المشكلة: واجهة R الأساسية قبيحة للغاية
استخدم بوب لغة R الأساسية لإنشاء رسم بياني يوضح اتجاهات المبيعات في أربع مدن:
plot(1:4, sales, type = "b")
ألقى المدير نظرة سريعة عليها وسأل: «هل يمكن إدراج هذه الصورة في التقرير؟»
(2) الحل باستخدام ggplot2
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) ما هي «قواعد الرسوم البيانية»؟
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() |
مثال بسيط:
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
4. أول رسم بياني باستخدام ggplot2
(1) عملية الرسم في 5 خطوات
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)
أو استخدم + لتنفيذ كل ذلك دفعة واحدة:
ggplot(df, aes(x = x, y = y)) +
geom_point() +
labs(title = "Quadratic Curve", x = "X", y = "Y") +
theme_minimal()
+ لربط الطبقات، على غرار استخدام |> لربط عمليات البيانات.
(2) الإخراج إلى ملف
# 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) التطبيق العملي: الخرائط ثلاثية الأبعاد
# 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() مقابل خارجها
# 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()
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() الرسم البياني الخطي
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() الرسم البياني الشريطي
# 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() الرسم البياني التكراري
# 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() الرسم البياني الصندوقي
# 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()
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() |
داكن |
# 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) ضبط التفاصيل الدقيقة للسمة
p + theme(
plot.title = element_text(size = 16, face = "bold"),
axis.text = element_text(size = 10),
legend.position = "bottom" # Legend Location
)
8. الألوان والتعيينات
(1) ألوان منفصلة
# 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) اللون المتواصل
# 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 صور
# ============================================
# 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")
الناتج المتوقع: 5 رسوم بيانية بجودة النشر (القالب الافتراضي «theme_minimal» جذاب بما فيه الكفاية بالفعل).
❓ أسئلة شائعة
geom_bar() وgeom_col()؟geom_bar(stat = "identity") قيمة y؛ أما geom_col() فهو «تسهيل نحوي» لها (أكثر إيجازًا). يتم العد في geom_bar() بشكل افتراضي (لا حاجة إلى y).geom_text() / geom_label():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 نقطة في البوصة هي المعيار القياسي للطباعة.📖 ملخص
- تعتمد مكتبة ggplot2 على قواعد الرسوم البيانية، وتقسم الرسوم البيانية إلى 7 طبقات (البيانات، والجماليات، والهندسة، والإحصاءات، والإحداثيات، والجوانب، والموضوعات)
- الركائز الثلاث:
ggplot()(البيانات) +aes()(التخطيط) +geom_xxx()(الطبقات) - 5 أنواع أساسية من الرسوم البيانية: نقطة / خط / شريط / مخطط تكراري / مخطط صندوقي
الرسم الخرائطي الجمالي:
colorfillsizeshapealphalinetype aes()من الداخل = تعيين متغير؛aes()من الخارج = قيمة ثابتة- استخدم
theme_minimal()وtheme_bw()وما إلى ذلك للموضوعات؛ واستخدمscale_color_brewer(palette = "Set1")للوحات الألوان ggsave()حفظ الصورة (dpi = 300، معيار الطباعة)- يوفر ggplot2 رسومًا بيانية بجودة النشر بشكل افتراضي — ويُستخدم في جميع التقارير والأوراق البحثية الاحترافية المكتوبة بلغة R
📝 تمارين
-
تمرين أساسي: أنشئ إطار بيانات (10 صفوف، وعمودين من قيم x و y)، واستخدم
ggplot + geom_point + labs + theme_minimalلرسم مخطط مبعثر، وتحقق من الفرق بينcolor = "red"(الداخل) وcolor = "red"(الخارج) فيaes(). -
تمرين أساسي: أنشئ مخططًا مبعثرًا باستخدام مجموعة البيانات
mtcars(wtمقابلmpg)، وقم بتلوين النقاط وفقًا لـcyl(color = factor(cyl))، وأضف عنوانًا وموضوعًا باستخدامlabs(). -
تمرين أساسي: أنشئ إطار بيانات (5 مدن + أرقام المبيعات)، واستخدم
geom_col()لرسم مخطط شريطي، وقم بفرز البيانات باستخدامreorder(city, sales)، وتحقق من نتائج الفرز. -
تمرين متقدم: قم بمحاكاة درجات الفصل 4 الذي يضم 30 طالبًا، واستخدم
geom_boxplot()لرسم مخطط توزيع الدرجات للفصل 4، وأضفfill = classلتحديد لون التعبئة وtheme_minimal()لتحديد السمة. -
التحدي: استخدم
mtcarsلإنشاء 6 رسوم بيانية (بالجمع بين نمطpar(mfrow)وggplot2): ① مخطط مبعثر لـ wt مقابل mpg ② رسم بياني تكراري لتوزيع wt ③ مخطط صندوقي لـ mpg ④ wt مقابل mpg حسب عدد الأسطوانات ⑤ مخطط مبعثر مع خريطة ألوان ⑥ تخصيص كامل للمظهر. احفظ الرسوم البيانية الستة بصيغة PDF.