【问题标题】:Equal coordinates and square aspect ratio with log scale in ggplotggplot中具有对数刻度的相等坐标和正方形纵横比
【发布时间】:2020-08-22 21:18:16
【问题描述】:

我正在尝试生成一组带有对数刻度轴和两个轴上相同坐标以及正方形纵横比的图。让我们考虑以下假设数据:

set.seed(1)
x <- rnorm(30, 50, 20)
y <- x + 20 + rnorm(30, 0, 10)

通过使用下面的代码,我得到了一个矩形图:

p <- qplot(x, y) + 
  scale_x_continuous(trans = "log2") + 
  scale_y_continuous(trans = "log2") + 
  coord_equal()

现在,如果我尝试使用 theme() 函数将纵横比强制为 1:1,它会破坏等坐标系:

p + theme(aspect.ratio = 1)

有没有办法同时获得相等的缩放比例和方形纵横比,这并不意味着手动更改每个图形的限制? 我需要将相同的代码应用于具有不同值和不同限制的一系列数据。

【问题讨论】:

    标签: r ggplot2 plot aspect-ratio


    【解决方案1】:

    默认情况下,ggplot2 将根据您的数据进行扩展。但是大多数scale_xxx 函数都提供了一个limits 参数,您可以对其进行微调。使用你上面的例子

    p <- qplot(x, y) + 
      scale_x_continuous(trans = "log2", limits=c(8,128)) + 
      scale_y_continuous(trans = "log2", limits=c(8,128)) + 
      coord_equal()
    p + theme( aspect.ratio=1 )
    

    如果您使用coord_fixed() 而不是coord_equal(),您也不需要提供theme

    p <- qplot(x, y) + 
      scale_x_continuous(trans = "log2", limits=c(8,128)) + 
      scale_y_continuous(trans = "log2", limits=c(8,128)) + 
      coord_fixed( ratio=1 )
    p
    

    编辑#1

    没有看到你们中的一个随机x点小于8。修改代码

    p <- qplot(x, y) + 
      scale_x_continuous(trans = "log2", limits=c(4,128)) + 
      scale_y_continuous(trans = "log2", limits=c(4,128)) + 
      coord_fixed( ratio=1)
    p
    

    EDIT #2(根据问题中的额外改写)

    如果您希望根据您的数据缩放范围,只需使用基础 R 中的range() 函数。所以使用上述变量...

    xy.limits <- range( c(x,y) )
    
    p <- qplot(x, y) + 
      scale_x_continuous(trans = "log2", limits=xy.limits) + 
      scale_y_continuous(trans = "log2", limits=xy.limits) + 
      coord_fixed( ratio=1)
    p
    
    

    现在,如果您想限制为 2 的纯倍数,那么您将不得不根据 xy.limits 的计算值进行一些数据操作,xy.limits 是一个长度为 2 的数字向量。

    【讨论】:

    • 我重新提出了我的问题,因为它不清楚。这里的数据不是我的真实数据,我正在尝试将其应用于具有不同限制的一整套值,因此无法手动设置每个图表的限制。
    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    相关资源
    最近更新 更多