简体   繁体   English

如何在ggplot2中将点大小调整为绘图的比例?

[英]How to adjust the point size to the scale of the plot in ggplot2?

Let's generate some data: 让我们生成一些数据:

x <- -10*cos(seq(0, pi, length.out = 100))+1
y <- 10*seq(0, pi, length.out = 100)
xerr <- rep(2, 100)
yerr <- rep(2, 100)
dd <- as.data.frame(cbind(x, y, xerr, yerr))

Here I have x and y coordinates of some points with their errors, xerr and yerr (for convenience I have set them constant). 这里我有一些点的xy坐标及其错误, xerryerr (为方便起见,我将它们设置为常量)。 I would like to represent these errors with the size of the points. 我想用点的大小来表示这些错误。 This is easily doable: 这很容易做到:

ggplot() + 
  geom_point(data = dd, aes(x, y, size = sqrt(xerr^2 + yerr^2)), colour = "gray") +
  geom_path(data = dd, aes(x, y), colour = "red", size = .5) +
  scale_size_identity() +
  theme_bw()

在此输入图像描述

However, the size of these points is defined on a scale that doesn't have any relation with the scale of the plot. 但是,这些点的大小是以与图的比例没有任何关系的比例定义的。 Is there a way to adjust the dimension of the points in relation to the scale of the plot? 有没有办法根据绘图的比例调整点的尺寸? In the above example, the radius of each point should have size equal to 2.828 and not less than one as it is now. 在上面的例子中,每个点的半径应该等于2.828并且不小于现在的1。

One way is to explicitly draw ellipses with the axes defined by the size of the errors. 一种方法是使用由错误大小定义的轴明确绘制椭圆。

x <- -10*cos(seq(0, pi, length.out = 10))+1
y <- 10*seq(0, pi, length.out = 10)
xerr <- runif(10, 1, 5)
yerr <- runif(10, 1, 5)
dd <- as.data.frame(cbind(x, y, xerr, yerr))
dd$frame <- factor(seq(1:10))

For this purpose we define our function to generate ellipses: 为此,我们定义了生成省略号的函数:

ellipseFun <- function(center = c(0, 0), axes = c(1, 1), npoints = 101){
  tt <- seq(0,2*pi, length.out = npoints)
  xx <- center[1] + axes[1] * cos(tt)
  yy <- center[2] + axes[2] * sin(tt)
  return(data.frame(x = xx, y = yy))
}

We then generate the matrices for all ellipses: 然后我们为所有省略号生成矩阵:

ddEll <- data.frame()
for(k in levels(dd$frame)){
  ddEll <- rbind(ddEll, cbind(as.data.frame(with(dd[dd$frame == k,], ellipseFun(center = c(x, y), axes = c(xerr, yerr), npoints = 101))),frame = k))
}

And, finally, we can plot them: 最后,我们可以绘制它们:

library(ggplot2)
ggplot() + 
  geom_point(data = dd, aes(x, y)) +
  geom_polygon(data=ddEll, aes(x = x, y = y, group = frame), colour = "gray", fill = "red", alpha = .2) +
  scale_size_identity() +
  theme_bw() +
  xlim(c(-20, 20)) + 
  ylim(c(-5, 35)) +
  coord_fixed()

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM