让我们生成一些数据:
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))
Run Code Online (Sandbox Code Playgroud)
在这里,我有x和y他们的错误的一些点的坐标,xerr和yerr(为方便起见,我已经将它们设置不变).我想用点的大小来表示这些错误.这很容易做到:
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()
Run Code Online (Sandbox Code Playgroud)

但是,这些点的大小是以与图的比例没有任何关系的比例定义的.有没有办法根据绘图的比例调整点的尺寸?在上面的例子中,每个点的半径应该等于2.828并且不小于现在的1.
一种方法是使用由错误大小定义的轴明确绘制椭圆.
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))
Run Code Online (Sandbox Code Playgroud)
为此,我们定义了生成省略号的函数:
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))
}
Run Code Online (Sandbox Code Playgroud)
然后我们为所有省略号生成矩阵:
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))
}
Run Code Online (Sandbox Code Playgroud)
最后,我们可以绘制它们:
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()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
2369 次 |
| 最近记录: |