2016-06-07 101 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