# 如何使用R語言ggplot2畫散點圖
## 一、ggplot2簡介
ggplot2是R語言中最著名的數據可視化包之一,由Hadley Wickham基于圖形語法(Grammar of Graphics)理論創建。它通過分層構建圖形的理念,讓用戶能夠以高度靈活的方式創建復雜的統計圖形。與R基礎繪圖系統相比,ggplot2具有以下優勢:
1. **一致的語法結構**:采用統一的圖層疊加語法
2. **豐富的圖形元素**:支持點、線、條、面等多種幾何對象
3. **自動化的圖例和坐標軸**:減少手動調整的工作量
4. **美觀的默認主題**:開箱即用的專業級圖表外觀
5. **強大的擴展性**:支持通過擴展包增加新功能
## 二、安裝與加載ggplot2
在開始之前,需要確保已安裝并加載ggplot2包:
```r
# 安裝ggplot2(如果尚未安裝)
install.packages("ggplot2")
# 加載包
library(ggplot2)
使用ggplot()函數初始化繪圖對象,geom_point()添加散點層:
# 使用內置數據集mtcars
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
這段代碼會創建一個以汽車重量(wt)為x軸、每加侖英里數(mpg)為y軸的散點圖。
ggplot2的基本語法模板:
ggplot(data = <DATA>,
mapping = aes(<MAPPINGS>)) +
<GEOM_FUNCTION>()
data: 使用的數據框mapping: 通過aes()定義的美學映射(aesthetic mappings)geom_*: 指定要繪制的幾何對象類型ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(size = 3, color = "blue")
# 按氣缸數(cyl)著色
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3)
# 按變速箱類型(am)改變形狀
ggplot(mtcars, aes(x = wt, y = mpg, shape = factor(am))) +
geom_point(size = 3)
ggplot(mtcars, aes(x = wt, y = mpg,
color = factor(cyl),
shape = factor(am))) +
geom_point(size = 3)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_hline(yintercept = 20, linetype = "dashed") +
geom_vline(xintercept = 3, linetype = "dotted")
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
labs(title = "汽車重量與油耗關系",
subtitle = "數據來自1974年Motor Trend雜志",
x = "重量(千磅)",
y = "油耗(英里/加侖)",
caption = "圖1: 基礎散點圖示例")
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
xlim(0, 6) +
ylim(10, 35)
或者使用coord_cartesian()實現縮放而不丟棄數據:
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
coord_cartesian(xlim = c(0, 6), ylim = c(10, 35))
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(alpha = 0.5) # 50%透明度
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_jitter(width = 0.1, height = 0.1)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
facet_wrap(~ cyl)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
theme_minimal() # 使用簡約主題
其他內置主題包括theme_bw(), theme_classic(), theme_dark()等。
my_theme <- theme(
plot.title = element_text(size = 16, face = "bold"),
axis.title = element_text(size = 12),
axis.text = element_text(color = "darkgray"),
panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(color = "lightgray")
)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
labs(title = "自定義主題示例") +
my_theme
ggsave("my_scatterplot.png",
width = 8,
height = 6,
dpi = 300)
# 加載數據
data(diamonds)
# 創建散點圖
ggplot(diamonds, aes(x = carat, y = price, color = cut)) +
geom_point(alpha = 0.3) +
geom_smooth(method = "loess", se = FALSE) +
facet_wrap(~ clarity) +
labs(title = "鉆石價格與重量關系",
x = "重量(克拉)",
y = "價格(美元)") +
theme_bw() +
theme(legend.position = "bottom")
確保在aes()中引用的變量名與數據框中的列名完全一致,包括大小寫。
使用theme(legend.position = "top"/"bottom"/"left"/"right"/"none")
geom_point(alpha = 0.1)降低透明度geom_hex()/geom_bin2d()替代使用expression()或bquote():
labs(x = expression(paste("重量(", mu, "g)")))
ggplot2提供了極其靈活和強大的散點圖繪制功能。通過掌握基礎語法和逐步添加各種圖層與修飾元素,您可以創建出專業級別的數據可視化作品。建議讀者多實踐不同的參數組合,探索ggplot2的更多可能性。
”`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。