R:使用轴缩放geom_point(ggplot2)

时间:2015-07-18 18:48:59

标签: r plot ggplot2

我编写了以下代码,用于在一组可重新缩放的轴上绘制我的x-y数据,pointSize中包含的值是每个绘制坐标所需点的正确缩放垂直/水平直径。我如何让这个工作?现在我只是使用geom_point(aes(size))默认使用的任何缩放来绘制点,并且这些点不会随轴缩放。一旦我用coord_cartesian重新缩放轴,我希望绘制的点相应地相对于轴增加/减少。

例如,如果点大小为5,则表示无论指定的xyScaling如何,我都希望点的水平和垂直直径相对于轴为5。

编辑:minS in pointSize应该是min = 0,而不是min = -10

最小可重现代码:

# Sample size & x-y axes plot boundaries
sampleSize <- 100

# Set scale factor of x-y axes
xyScaling <- 1

# Set to false once sampled to rescale axis with same distributions
resample <- TRUE

if (resample == TRUE){
  xSample <- replicate(sampleSize, runif(1, min = -sampleSize/2, max = sampleSize/2))

  ySample <- replicate(sampleSize, runif(1, min = -sampleSize/2, max = sampleSize/2))

  pointSize <- replicate(sampleSize, runif(1, min = 0, max = 10))
}

sampleDataFrame <- data.frame(xSample, ySample, pointSize)
samplePlot <- ggplot(sampleDataFrame, aes(xSample, ySample))
samplePlot +
geom_point(data = sampleDataFrame, aes(size = sampleDataFrame$pointSize[])) + 
coord_cartesian(xlim = c((xyScaling*(-sampleSize/2)),(xyScaling*(sampleSize/2))),
                ylim = c((xyScaling*(-sampleSize/2)),(xyScaling*(sampleSize/2)))) +
xlab("x") +
ylab("y") +
scale_size_identity(guide=FALSE)

编辑:所以我几乎设法通过使用geom_rect来解决问题,下面的代码做了我想要的,但需要注意的是点是矩形而不是椭圆/圆圈,我无法使用它来处理椭圆,如果有人能指导我正确的功能,我将非常感激。

sampleDataFrame <- data.frame(xSample, ySample, pointSize)

samplePlot <- ggplot(sampleDataFrame)
samplePlot +
  geom_point(aes(xSample, ySample, size = 0)) + 
  geom_rect(aes(xmin = xSample-(pointSize/2), xmax = xSample+(pointSize/2), ymin = ySample-(pointSize/2), ymax = ySample+(pointSize/2))) +
  coord_cartesian(xlim = c((xyScaling*(-sampleSize/2)),(xyScaling*(sampleSize/2))),
                  ylim = c((xyScaling*(-sampleSize/2)),(xyScaling*(sampleSize/2)))) +
  xlab("x") +
  ylab("y") +
  scale_size_identity(guide=FALSE)

2 个答案:

答案 0 :(得分:1)

has been suggested in the past,但我认为它没有得到实施。一个问题是,在具有单位纵横比的笛卡尔坐标的特殊情况下,圆仅是圆形的。最简单的解决方法可能是创建一个data.frame,其中xy位置描述圆(椭圆)并将它们绘制为多边形。

library(gridExtra)
library(ggplot2)

circle <- polygon_regular(50)

pointy_points <- function(x, y, size){
  do.call(rbind, mapply(function(x,y,size,id) 
    data.frame(x=size*circle[,1]+x, y=size*circle[,2]+y, id=id),
         x=x,y=y, size=size, id=seq_along(x), SIMPLIFY=FALSE))

}

test <- pointy_points(1:10, 1:10, size=seq(0.2, 1, length.out=10))

ggplot(test, aes(x,y,group=id, fill=id)) + geom_polygon()

enter image description here

答案 1 :(得分:1)

您可以尝试编辑最低级别的点,但它非常繁琐,

library(ggplot2); library(grid)
p <- qplot(1:10, 1:10, size=I(10))
g <- ggplotGrob(p)

points <- g$grobs[[4]][["children"]][[2]]
g$grobs[[4]][["children"]][[2]] <- 
  editGrob(points, size = convertUnit(points$size, unitTo = "npc"))

grid.newpage()
grid.draw(g)