R中条形图的重心
Center of gravity of barplot in R
假设你有一个向量,并在 R 中绘制了它的条形图。你如何计算条形图的质心 / center of gravity?
x<-cumsum(rnorm(50,1,2))
par(mfrow=c(1,2))
plot(x,type="l")
barplot(x)
par(mfrow=c(1,1))
这里有很多关于 polygon, but I'm not sure which points I need to get the entire shape of the barplot, and not just the vector with the points (like in the left plot) 重心的答案。
每个柱的质心都在其几何中心,因此您可以使用“A_system_of_particles”的方法。
M = Sum(Height[i]) for all i
cx = Sum(Height[i] * i) / M
cy = Sum(Height[i] * Height[i] / 2) / M
您可以使用此函数轻松计算它
getCentroid <- function(x, width = 1) {
A <- x * width # area of each bar
xc <- seq(width/2, length(x), 1) # x coordinates of center of bars
yc <- x/2 # y coordinatey
cx <- sum(xc * A) / sum(A)
cy <- sum(yc * A) / sum(A)
return(list(x = cx, y = cy))
}
points(getCentroid(x), col = 'red', pch = 19)
注意:每个条的默认宽度为1。两个条的质心的x坐标可以使用公式
计算
y坐标也是如此。这可以扩展到更多的柱。
由于我们没有完美的三角形,所以比较质心总会有误差。以高度差相同的条为例,如
x <- seq(0, 1, length.out = 1000)
(第一个柱的高度为 0)将始终在 x 坐标中产生 1/6 的误差(2000/3 与 666.83333 相比)。原因是由于我们没有完美的三角形而导致缺少区域。这个缺失的区域等于 0.5(考虑高度差并将其乘以条宽度。将所有条的总和除以 2 等于....)。
假设你有一个向量,并在 R 中绘制了它的条形图。你如何计算条形图的质心 / center of gravity?
x<-cumsum(rnorm(50,1,2))
par(mfrow=c(1,2))
plot(x,type="l")
barplot(x)
par(mfrow=c(1,1))
这里有很多关于 polygon, but I'm not sure which points I need to get the entire shape of the barplot, and not just the vector with the points (like in the left plot) 重心的答案。
每个柱的质心都在其几何中心,因此您可以使用“A_system_of_particles”的方法。
M = Sum(Height[i]) for all i
cx = Sum(Height[i] * i) / M
cy = Sum(Height[i] * Height[i] / 2) / M
您可以使用此函数轻松计算它
getCentroid <- function(x, width = 1) {
A <- x * width # area of each bar
xc <- seq(width/2, length(x), 1) # x coordinates of center of bars
yc <- x/2 # y coordinatey
cx <- sum(xc * A) / sum(A)
cy <- sum(yc * A) / sum(A)
return(list(x = cx, y = cy))
}
points(getCentroid(x), col = 'red', pch = 19)
注意:每个条的默认宽度为1。两个条的质心的x坐标可以使用公式
计算y坐标也是如此。这可以扩展到更多的柱。
由于我们没有完美的三角形,所以比较质心总会有误差。以高度差相同的条为例,如
x <- seq(0, 1, length.out = 1000)
(第一个柱的高度为 0)将始终在 x 坐标中产生 1/6 的误差(2000/3 与 666.83333 相比)。原因是由于我们没有完美的三角形而导致缺少区域。这个缺失的区域等于 0.5(考虑高度差并将其乘以条宽度。将所有条的总和除以 2 等于....)。