《R數(shù)據(jù)可視化手冊》學習筆記2---快速探索數(shù)據(jù)(2)折線圖

寫在前面。

很多時候在處理數(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建立了一個圖層并繪制了一條折線,pointslines在圖層之上又添加圖層和元素。

  • 使用ggplot2qplot函數(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()

以上。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容