R for data science的一些筆記
原書地址:3 Data visualisation | R for Data Science (had.co.nz)
對數(shù)據(jù)集進行簡單的可視化茄茁,可用以下通式,其中GEO_FUNCTION
部分輸入ggplot2中不同繪圖方法的函數(shù)名裙顽,如geom_point
ggplot (data = <DATA> ) +
<GEO_FUNCTION>(mapping = aes(<MAPPINGS>))
aes()
用來對geom function進行描述,如定義x與y軸數(shù)據(jù)键科,同時可以使用color
,scale
,alpha
,shape
等參數(shù)漩怎,對指定分類進行顏色、大小勋锤、深淺以及圖標形狀的設(shè)定。應(yīng)注意的是茄厘,當指定分類變量為無序變量時谈宛,使用有序scale
來繪制是不合適的。而對于shape
而言吆录,ggplot2一次只能提供6中形狀,當類別數(shù)量超過6時哀卫,超過部分將不予繪制。
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, color = class))
#use different colors according to the class
ggplot(data = mpg) +
geom_point(mapping = aes(x = cty, y = hwy, colour = displ < 5))
#classify the observations which displ<5 with different color
當然聊训,上述變量也可單獨設(shè)置恢氯,如設(shè)定繪制顏色為藍色,則輸入color = 'blue'
即可勋磕。此時敢靡,color
,scale
,alpha
,shape
應(yīng)輸入在aes()
外部,且顏色形狀等不再傳遞分類的數(shù)據(jù)意義啸胧。
#one can try and will find the following two functions have different results.
#the points will be showed in red.
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, color = "blue"))
#the points will be showed in blue.
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy), color = "blue")
geom_point()
中還有stroke
參數(shù),用以表述圖標的輪廓粗細贝椿,此時colour
表示輪廓顏色陷谱,而fill
表示填充顏色。
ggplot(mtcars, aes(wt, mpg)) +
geom_point(shape = 21, colour = "black", fill = "white", size = 5, stroke = 1)
facets
是一種烟逊,在原有畫布上增加變量的一種方式。facet_wrap()
在括號內(nèi)使用~
連接變量(當使用該函數(shù)時乔宿,應(yīng)針對離散型變量)访雪,facet_grid()
是另一種增加變量的方式,但需要輸入兩個變量冬阳,中間以~
連接,變量會出現(xiàn)在橫縱軸上驳庭,若只需要一個,可在另一個位置上輸入.
代替變量名饲常。
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ cyl)