【问题标题】:Preserving aspect ratio in R's grid graphics在 R 的网格图形中保留纵横比
【发布时间】:2014-06-17 17:29:45
【问题描述】:

使用我调用的低级 graphics 封装工具绘制一个高度比宽度大 2 倍的“交叉”矩形:

xlim <- c(0, 500)
ylim <- c(0, 1000)
plot.new()
plot.window(xlim, ylim, asp=1)
rect(xlim[1], ylim[1], xlim[2], ylim[2])
lines(c(xlim[1], xlim[2]), c(ylim[1], ylim[2]))
lines(c(xlim[1], xlim[2]), c(ylim[2], ylim[1]))

该图有一个很好的功能:保留了纵横比,因此如果我更改绘图窗口的大小,我会得到相同的高宽比例。

如何获得与grid 图形相同的结果?

【问题讨论】:

    标签: r plot r-grid


    【解决方案1】:

    您应该创建一个使用 Square Normalized Parent Coordinates 的视口, 见?unit:

    "snpc": (...) 这对于制作成比例的东西很有用 视口,但必须是方形的(或具有固定的纵横比)。

    代码如下:

    library('grid')
    xlim <- c(0, 500)
    ylim <- c(0, 1000)
    grid.newpage() # like plot.new()
    pushViewport(viewport( # like plot.window()
            x=0.5, y=0.5, # a centered viewport
            width=unit(min(1,diff(xlim)/diff(ylim)), "snpc"), # aspect ratio preserved
            height=unit(min(1,diff(ylim)/diff(xlim)), "snpc"),
            xscale=xlim, # cf. xlim
            yscale=ylim  # cf. ylim
    ))
    # some drawings:
    grid.rect(xlim[1], ylim[1], xlim[2], ylim[2], just=c(0, 0), default.units="native")
    grid.lines(xlim, ylim, default.units="native")
    grid.lines(xlim, rev(ylim), default.units="native")
    

    default.units 参数在例如grid.rect 强制绘图功能 使用本机 (xscale/yscale) 视口坐标。 just=c(0, 0) 表示xlim[1], ylim[1] 表示左下节点 矩形。

    【讨论】:

      【解决方案2】:

      ggplot2(基于grid)中,您可以使用coord_fixed() 修复纵横比:

      library(ggplot2)
      ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + coord_fixed(ratio = 0.5)
      

      这将固定比率,即使更改图形窗口的大小,比率也会保持不变。

      我不确定这是否有帮助,因为您要求提供基于 grid 的低级解决方案。但我认为它可能仍然有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-17
        • 1970-01-01
        • 1970-01-01
        • 2015-07-16
        相关资源
        最近更新 更多