一、qplot函數app
> library(ggplot2) > head(diamonds) carat cut color clarity depth table price x y z 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31 3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31 4 0.29 Premium I VS2 62.4 58 334 4.20 4.23 2.63 5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75 6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48 > set.seed(1410) #讓樣本可重複 > dsmall<-diamonds[sample(nrow(diamonds),100),] #建立一個容量爲100的隨機樣本 > qplot(carat,price,data=diamonds) #繪製散點圖
qplot(carat,log(price),data=diamonds) #qplot()支持變量的函數做爲參數
> qplot(carat,log(price),data=diamonds,colour=color) #向散點圖添加顏色信息
> qplot(carat,log(price),data=diamonds,shape=cut) #向散點圖添加形狀信息
> qplot(color,data=diamonds,geom="bar") #繪製條形圖
二、ggplot2函數ide
ggplot(data = , aes(x = , y = )) + geom_XXX(...) + #geom :表示幾何對象,負責圖形渲染的類型 ... + stat_XXX(...) + #統計變換 好比求均值,求方差等,當咱們須要展現出某個變量的某種統計特徵的時候,須要用到統計變換 ... + annotate(...) + #添加註釋 #因爲設置的文本會覆蓋原來的圖中對應的位置,能夠改變文本的透明度或者顏色 例: annotate(geom='text')會向圖形添加一個單獨的文本對象 ... + labs(...) + #labs(x = "這是 X 軸", y = "這是 Y 軸", title = "這是標題") scale_XXX(...) + #標度 coord_XXX(...) + #調整座標,調整座標 coord_flip()來翻轉座標軸。使用xlim()和ylim()來設置連續型座標軸的最小值和最大值 guides(...) + #調整全部的text theme(...) + #調整不與數據有關的圖的元素的函數。theme函數採用了四個簡單地函數來調整全部的主題特徵:element_text調整字體,element_line調整主題內的全部線,element_rect調整全部的塊,element_blank清空。theme(panel.grid =element_blank()) ## 刪去網格線 facet_XXX(...) #控制分組繪圖的方法和排列形式
條形圖函數
> x <- c('A','B','C','D','E') > y <- c(13,22,16,31,8) > df <- data.frame(x= x, y = y) > df x y 1 A 13 2 B 22 3 C 16 4 D 31 5 E 8 > ggplot(data = df, mapping = aes(x = x, y = y)) + geom_bar(stat= 'identity') #對於條形圖的y軸就是數據框中本來的數值時,必須將geom_bar()函數中stat(統計轉換)參數設置爲’identity’,即對原始數據集不做任何統計變換,而該參數的默認值爲’count’,即觀測數量。
使用明細數據集繪製條形圖:字體
> set.seed(1234) > x <- sample(c('A','B','C','D'), size = 20, replace= TRUE, prob = c(0.2,0.3,0.3,0.2)) > y <- rnorm(1000) * 100 > df <- data.frame(x= x, y = y) > head(df,20) x y 1 B -47.719 2 D -99.839 3 D -77.625 4 D 6.446 5 A 95.949 6 D -11.029 7 B -51.101 8 B -91.120 9 D -83.717 10 C 241.584 11 D 13.409 12 C -49.069 13 B -44.055 14 A 45.959 15 B -69.372 16 A -144.820 17 B 57.476 18 B -102.366 19 B -1.514 20 B -93.595