制作三元图

Bea*_*eld 11 r ggplot2

我想使用ggplot2绘制三维数据在单纯形图上的投影.我以为我可以使用笛卡尔坐标来管理变换coord_trans(),但不知道如何准确地完成它.

这是我试过的:

simplex.y  <- function( x1, x2, x3 ) {
  return( sqrt(0.75) *  x3 / (x1+x2+x3) )
} 
simplex.x  <- function( x1, x2, x3 ) {
  return( (x2 + 0.5 * x3) / (x1+x2+x3) )
}

x  <- data.frame(
  x1 = c( 0, 0, 1, 0.1, 0.6, 0.2 ),
  x2 = c( 0, 1, 0, 0.3, 0.2, 0.8 ),
  x3 = c( 1, 0, 0, 0.6, 0.2, 0.0 )
)

require(ggplot2)
ggplot( data = x, aes( x = c(x1, x2, x3), y = c(x1, x2, x3)) ) +
  geom_point() +
  coord_trans( x="simplex.x", y="simplex.y" )
Run Code Online (Sandbox Code Playgroud)

任何建议表示赞赏.非常感谢!

Nic*_*ton 14

正如mmann1123强调的那样,使用ggtern,可以实现以下目标:

产量

使用以下简单的代码块:

x  <- data.frame(
  x1 = c( 0, 0, 1, 0.1, 0.6, 0.2 ),
  x2 = c( 0, 1, 0, 0.3, 0.2, 0.8 ),
  x3 = c( 1, 0, 0, 0.6, 0.2, 0.0 )
)

ggtern(data=x,aes(x2,x1,x3)) + 
   geom_mask() +
   geom_point(fill="red",shape=21,size=4) + 
   theme_bw() +
   theme_showarrows() +
   theme_clockwise()
Run Code Online (Sandbox Code Playgroud)


Dre*_*een 5

vcd包中的三元图函数可以很好地根据非标准化数据制作经典的三元图:

require(vcd)
#ternaryplot takes matrices but not data frames
xM <- as.matrix(x)
ternaryplot(xM)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


jor*_*ran 1

coord_trans并没有像你想象的那样做。它将转换已经是 2D 但您有 3D 数据的绘图的 x 和 y 坐标。

只需自己转换数据,然后绘制它:

simplex.y  <- function(x) {
  return( sqrt(0.75) *  x[3] / sum(x) )
} 
simplex.x  <- function(x) {
  return( (x[2] + 0.5 * x[3]) / sum(x) )
}

x  <- data.frame(
  x1 = c( 0, 0, 1, 0.1, 0.6, 0.2 ),
  x2 = c( 0, 1, 0, 0.3, 0.2, 0.8 ),
  x3 = c( 1, 0, 0, 0.6, 0.2, 0.0 )
)

newDat <- data.frame(x = apply(x,1,simplex.x),
                y = apply(x,1,simplex.y))

ggplot(newDat,aes(x = x,y = y)) + 
    geom_point()
Run Code Online (Sandbox Code Playgroud)

请注意,我重写了您的转换函数,使其更像 R。另外,您不应该传递像x = c(x1,x2,x3)inside of 之类的表达式aes()。您将数据框中的单个变量映射到单个美学。