天天看點

R語言 plot swimmer_R語言之可視化⑤R圖形系統

目錄

R語言之可視化⑤R圖形系統

======================================

R中有不同的圖形包可用于可視化您的資料:1) R base graphs, 2) Lattice Graphs (Sarkar 2016) and 3) ggplot2 (Wickham and Chang 2017).

R base graphs

R帶有簡單的函數來建立許多類型的圖形。 例如:

R語言 plot swimmer_R語言之可視化⑤R圖形系統

在大多數情況下,您可以使用以下參數來自定義繪圖:

pch:改變點形狀。 允許值包括1到25之間的數字。

cex:改變點大小。 示例:cex = 0.8。

col:改變點顔色。 示例:col =“blue”。

frame:邏輯值。 frame = FALSE删除繪圖面闆邊框。

main,xlab,ylab。 分别指定主标題和x / y軸标簽

las:對于垂直x軸文本,使用las = 2。

在下面的R代碼中,我們将使用iris資料集來建立:

首先我們繪制一個以iris

R語言 plot swimmer_R語言之可視化⑤R圖形系統

Sepal.Width的散點圖

# (1) Create a scatter lot

plot(

x = iris$Sepal.Length, y = iris$Sepal.Width,

pch = 19, cex = 0.8, frame = FALSE,

xlab = "Sepal Length",ylab = "Sepal Width"

)

R語言 plot swimmer_R語言之可視化⑤R圖形系統

image.png

其次,我們繪制了一個盒須圖

# (2) Create a box plot

boxplot(Sepal.Length ~ Species, data = iris,

ylab = "Sepal.Length",

frame = FALSE, col = "lightgray")

R語言 plot swimmer_R語言之可視化⑤R圖形系統

Lattice graphics

提供了一個繪圖系統,旨在改進R基本圖形。 安裝軟體包後,使用R指令install.packages(“lattice”)。格子包中的主要功能:

R語言 plot swimmer_R語言之可視化⑤R圖形系統

建立y乘以x的基本散點圖。 文法:y~x。 按組更改顔色并使用auto.key = TRUE顯示圖例:

library("lattice")

xyplot(

Sepal.Length ~ Petal.Length, group = Species,

data = iris, auto.key = TRUE, pch = 19, cex = 0.5

)

R語言 plot swimmer_R語言之可視化⑤R圖形系統

根據分組繪制多個面闆圖:y ~ x | group.

xyplot(

Sepal.Length ~ Petal.Length | Species,

layout = c(3, 1), # panel with ncol = 3 and nrow = 1

group = Species, data = iris,

type = c("p", "smooth"), # Show points and smoothed line

scales = "free" # Make panels axis scales independent

)

R語言 plot swimmer_R語言之可視化⑤R圖形系統

ggplot2圖形

GGPlot2是一個功能強大且靈活的R軟體包,由Hadley Wickham實作,用于逐件生成優雅的圖形。 ggplot2中的gg表示圖形文法,這是一個圖形概念,通過使用“文法”來描述圖。根據ggplot2概念,繪圖可以分為不同的基本部分:Plot = data + Aesthetics + Geometry

data:資料框

Aesthetics :用于表示x和y變量。它還可以用來控制點的顔色,大小和形狀等......

geometry:對應于圖形類型(直方圖,箱形圖,線圖,......)

對于初學者來說,ggplot2文法可能看起來不透明,但是一旦了解了基礎知識,就可以建立和自定義任何類型的圖表。

R語言 plot swimmer_R語言之可視化⑤R圖形系統

ggplot2包中的主要功能是ggplot(),它可用于使用資料和x / y變量初始化繪圖系統。