代码之家  ›  专栏  ›  技术社区  ›  Timo

ggplot2刻面边缘

  •  9
  • Timo  · 技术社区  · 14 年前

    我使用 facet_wrap 绘制一些数据。以下是一个示例:

    library (ggplot2)
    library (reshape)
    
    # generate some dummy data
    x = seq(0,1,0.05)
    precision = sqrt(x)
    recall    = 1 - precision
    fmeasure  = 2 * (precision * recall) / (precision + recall)
    
    # prepare it for plotting
    df = data.frame(x=x, precision=precision, recall=recall, fmeasure=fmeasure)
    df = melt(df, id.vars=c(x))
    
    # plot it
    p = ggplot(df, aes(x=x, y=value, group=variable))
    p = p + geom_line() + facet_wrap(~variable, ncol=3)
    p = p + coord_cartesian(xlim=c(0,1), ylim=c(0,1)) # second plot is without this line
    print (p)
    

    图1:上述代码的绘图。 Plot with xlim and ylim

    然而,您在图1中看到的是,后续方面的第一个和最后一个标签重叠。这可以通过增加刻面之间的空间来解决。其他选项是删除 xlim 和 ylim 范围,如图2所示,但这在方面本身保留了不必要的空间。

    图2:折线图 p = p + coord_cartesian(xlim=c(0,1), ylim=c(0,1)) 已删除。 Plot without xlim and ylim

    我试着增加各方面之间的空间,但到目前为止我一直无法做到。你有什么建议吗?

    我使用ggplot2版本0.9.1。

    2 回复  |  直到 14 年前
        1
  •  10
  •   Tyler Rinker DaniM    8 年前

    对于0.9.1使用: p + opts(panel.margin = unit(2, "lines")) 但是你有很多额外的空白,IMO失去了一些贴面的效果(注0.9.2现在使用 theme 而不是 opts )

    多年来,ggplot2 API发生了变化,截至2018-02-01,这是更新的解决方案:

    p + theme(panel.spacing = unit(2, "lines"))
    
        2
  •  1
  •   Megatron    5 年前

    根据Tyler的回答,您可以使用 strip.text 主题参数如下:

    library(tidyverse)
    
    mpgTidy <- pivot_longer(mpg, c(cty, hwy), names_to="mpg_categ", values_to="mpg")
    
    g <- ggplot(mpgTidy, aes(x=displ, y=mpg, color=factor(cyl))) +
      facet_wrap(~ mpg_categ) +
      geom_point()
    
    g
    

    enter image description here

    g + theme(strip.text=element_text(margin=margin()),
              panel.spacing=unit(0, "lines"))
    

    enter image description here

    当分面标签很长或包含换行符并且分面图同时具有行和列时,这可能很有用。

    推荐文章