寫在前面。
很多時候在處理數(shù)據(jù)前或者出圖前,可能需要先對數(shù)據(jù)整體情況進行了解。這個時候我們可以用到R基礎繪圖的語句
和ggplot2
完成目標。
接下來,我們分不同的圖形類型
進行啃書學習。
2. 繪制折線圖
如何繪制折線圖?
使用R內(nèi)置數(shù)據(jù)集pressure
作為示例數(shù)據(jù)。
> str(pressure)
'data.frame': 19 obs. of 2 variables:
$ temperature: num 0 20 40 60 80 100 120 140 160 180 ...
$ pressure : num 0.0002 0.0012 0.006 0.03 0.09 0.27 0.75 1.85 4.2 8.8 ...
- 使用R基礎繪圖系統(tǒng)
使用plot()
函數(shù),同時添加參數(shù)type="l"
plot(pressure$temperature, pressure$pressure, type = "l")
基礎繪圖系統(tǒng)繪制的散點圖
如果我們要給線上加上散點
,同時再繪制一條紅色折線并加上紅色的散點
,則使用如下語句,其中,dev.off()
清除繪圖板上已有的圖像。
dev.off()
plot(pressure$temperature, pressure$pressure, type = "l")
points(pressure$temperature, pressure$pressure)
lines(pressure$temperature, pressure$pressure/2, col = "red")
points(pressure$temperature, pressure$pressure/2, col = "red")
基礎繪圖系統(tǒng)繪制的折線散點圖
如果用圖層思想
理解,相當于plot
建立了一個圖層并繪制了一條折線,points
和lines
在圖層之上又添加圖層和元素。
- 使用ggplot2的
qplot
函數(shù)
通過在qplot
函數(shù)中添加選項geom='line'
指定繪制圖形的幾何學類型,geom
就是幾何學geometry
的縮寫。
qplot(pressure$temperature, pressure$pressure, geom = "line")
qplot函數(shù)繪制的折線圖
如果要給線上加上散點,則添加參數(shù)geom = c("line" ,"point")
:
qplot(pressure$temperature, pressure$pressure, geom = c("line" ,"point"))
qplot函數(shù)繪制的折線散點圖
上述語句等價于我們在使用ggplo2繪圖時更常用的語句形式:
ggplot(data = pressure, aes(temperature, pressure)) + geom_line() + geom_point()
以上。