R包——ggplot2(二)

來源:互聯網
上載者:User

標籤:

關於ggplot包(二) 關於ggplot包(二)尺規(Scale)

從前面可以看到,畫圖其實就是在做映射,不管是映射到不同的幾何對象上,還是映射各種圖形屬性。在對圖形屬性進行映射之後,使用尺規可以控制這些屬性的顯示方式,如座標刻度,如顏色屬性。

> ggplot(small)+geom_point(aes(x=carat,y=price,shape=cut,colour=color))+scale_y_log10()+scale_colour_manual(values=rainbow(7))#將Y軸座標進行log10變換,自己定義顏色為彩虹色

統計變換(Statistics)

統計變換對未經處理資料進行某種計算,然後在圖上表示出來,如對散佈圖上加一條迴歸線

> ggplot(small,aes(x=carat,y=price))+geom_point()+scale_y_log10()+stat_smooth()

這裡,aes所提供的參數,就通過ggplot提供,而不是提供給geom_point,因為ggplot裡的參數,相當於全域變數,geom_point()和stat_smooth()都知道x,y的映射,如果只提供給geom_point(),則相當於是局部變數,geom_point知道這種映射,而stat_smooth不知道,當然你再給stat_smooth也提供x,y的映射,不過共用的映射,還是提供給ggplot好。
ggplot2提供了多種統計變換方式:

stat_abline       stat_contour      stat_identity     stat_summary
stat_bin stat_density stat_qq stat_summary2d
stat_bin2d stat_density2d stat_quantile stat_summary_hex
stat_bindot stat_ecdf stat_smooth stat_unique
stat_binhex stat_function stat_spoke stat_vline
stat_boxplot stat_hline stat_sum stat_ydensity
座標系統(Coordinante)

座標系統控制座標軸,可以進行變換,如XY軸翻轉,笛卡爾座標和極座標轉換。
座標軸翻轉由coord_flip()實現

> ggplot(small)+geom_bar(aes(x=cut,fill=cut))+coord_flip()


而轉換成極座標可以由coord_polar()實現:

> ggplot(small)+geom_bar(aes(x=factor(1), fill=cut))+coord_polar(theta="y")

還可以畫靶心圖

> ggplot(small)+geom_bar(aes(x=factor(1), fill=cut))+coord_polar()

風玫瑰圖

> ggplot(small)+geom_bar(aes(x=clarity, fill=cut))+coord_polar()

圖層(Layer)

對於PS的圖層概念,ggplot也能使用+號來疊加圖層

分面(Facet)

分面可以讓我們按照某種給定的條件,對資料進行分組,然後分別畫圖

> ggplot(small, aes(x=carat, y=price))+geom_point(aes(colour=cut))+scale_y_log10() +facet_wrap(~cut)+stat_smooth()

主題(Theme)

通過ggplot畫圖之後,我們可能還需要對圖進行定製,像title, xlab, ylab這些高頻需要用到的,自不用說,ggplot2提供了ggtitle(), xlab()和ylab()來實現。

但是這個遠遠滿足不了需求,我們需要改變字型,字型大小,座標軸,背景等各種元素,這需要通過theme()函數來完成。

ggplot2提供一些已經寫好的主題,比如theme_grey()為預設主題,theme_bw()為白色背景的主題,還有theme_classic()主題,和R的基礎畫圖函數較像。

別外ggthemes包提供了一些主題可供使用,包括:

theme_economist theme_economist_white
theme_wsj theme_excel
theme_few theme_foundation
theme_igray theme_solarized
theme_stata theme_tufte
> p<-ggplot(small)+geom_boxplot(aes(x=cut, y=price,fill=color))
> p
> require(ggthemes)
載入需要的程輯包:ggthemes
> p + theme_wsj()


詳細說明,可以參考?theme的協助文檔

二維密度圖
> ggplot(diamonds, aes(carat, price))+ stat_density2d(aes(fill = ..level..), geom="polygon")+ scale_fill_continuous(high=‘darkred‘,low=‘darkgreen‘)

R包——ggplot2(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.