2016-06-07 62 views
1

我有一組能產生多條曲線碼小數位採用facet_wrapfacet_wrap標題包裹&上free_y軸線(GGPLOT2)

ggplot(summ,aes(x=depth,y=expr,colour=bank,group=bank)) + 
geom_errorbar(aes(ymin=expr-se,ymax=expr+se),lwd=0.4,width=0.3,position=pd) + 
geom_line(aes(group=bank,linetype=bank),position=pd) + 
geom_point(aes(group=bank,pch=bank),position=pd,size=2.5) + 
scale_colour_manual(values=c("coral","cyan3", "blue")) + 
facet_wrap(~gene,scales="free_y") + 
theme_bw() 

隨着參考數據集,該代碼產生的數字是這樣的:

multiplot example

我想在這裏實現兩個目標:

  1. 保持y軸的自動縮放,但要確保在所有圖中只顯示1個小數位。我曾嘗試創建一個圓整的expr值的新列,但它會導致錯誤欄未正確排列。
  2. 我想包裝標題。我曾嘗試更改Change plot title sizes in a facet_wrap multiplot中的字體大小,但某些基因名稱太長,如果我將它們塞在一行中,結果太小而無法讀取。有沒有辦法使用facet_wrap聲明中的代碼來包裝文本?

回答

1

也許不能作爲確切的答案,但這裏有關於你的問題,一些指點:

  1. 格式化y軸刻度標籤。

首先,讓我們嘗試使用format函數的直接解決方案。在此,我們將所有y軸刻度標籤格式化爲具有1個十進制值,然後用round四捨五入。

formatter <- function(...){ 
    function(x) format(round(x, 1), ...) 
} 

mtcars2 <- mtcars 
sp <- ggplot(mtcars2, aes(x = mpg, y = qsec)) + geom_point() + facet_wrap(~cyl, scales = "free_y") 
sp <- sp + scale_y_continuous(labels = formatter(nsmall = 1)) 

enter image description here

的問題是,有時這種做法是不實際的。例如,從你的圖中最左邊的圖上。使用相同的格式,所有y軸刻度標籤都會四捨五入到-0.3,這不是優選的。

另一種解決方案是將每個繪圖的中斷修改爲一組四捨五入的值。但是,再次以圖中最左側的圖爲例,它最終只有一個標籤點,-0.3

另一種解決方案是將標籤格式化爲科學形式。爲簡單起見,你可以修改formatter功能如下:

formatter <- function(...){ 
    function(x) format(x, ..., scientific = T, digit = 2) 
} 

enter image description here

現在你可以對所有地塊y軸的統一格式。然而,我的建議是在四捨五入後將標籤設置爲2位小數。


  • 裹面標題
  • 這可以在使用facet_wrap參數labeller來完成。

    # Modify cyl into factors 
    mtcars2$cyl <- c("Four Cylinder", "Six Cylinder", "Eight Cylinder")[match(mtcars2$cyl, c(4,6,8))] 
    
    # Redraw the graph 
    sp <- ggplot(mtcars2, aes(x = mpg, y = qsec)) + geom_point() + 
        facet_wrap(~cyl, scales = "free_y", labeller = labeller(cyl = label_wrap_gen(width = 10))) 
    sp <- sp + scale_y_continuous(labels = formatter(nsmall = 2)) 
    

    enter image description here

    必須注意的是,纏繞功能檢測空間標籤分離成線。所以,就你而言,你可能需要修改你的變量。

    +1

    感謝您的全面迴應!我決定離開Y軸,因爲一些地塊比其他地方需要更多的小數位。至於包裝標題,我使用'data $ gene < - gsub('_','',data $ gene)'用空格替換所有_。然後,通過在我的'facet_wrap'聲明中加入'labeller = labeller(gene = label_wrap_gen(width = 30)',我能夠成功地包裝基因名稱。再次感謝! –

    +0

    @MichaelStudivan好極了! – zyurnaidi

    1

    這隻解決了問題的第一部分。您可以創建一個函數來格式化軸,並使用scale_y_continous進行調整。

    df <- data.frame(x=rnorm(11), y1=seq(2, 3, 0.1) + 10, y2=rnorm(11)) 
    
    library(ggplot2) 
    library(reshape2) 
    
    df <- melt(df, 'x') 
    
    # Before 
    ggplot(df, aes(x=x, y=value)) + geom_point() + 
        facet_wrap(~ variable, scale="free") 
    

    enter image description here

    # label function 
    f <- function(x){ 
        format(round(x, 1), nsmall=1) 
    } 
    
    # After 
    ggplot(df, aes(x=x, y=value)) + geom_point() + 
        facet_wrap(~ variable, scale="free") + 
        scale_y_continuous(labels=f) 
    

    enter image description here