2012-05-03 13 views
9

Voglio tracciare la proiezione di dati tridimensionali sul loro simplex utilizzando ggplot2. Pensavo di poter gestire la trasformazione su coordinate cartesiane usando coord_trans(), ma non so come farlo esattamente.Creazione di un grafico ternario

Questo è quello che ho provato:

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") 

Tutti i suggerimenti sono apprezzati. Grazie molto!

+0

Vedi anche [Come installare il pacchetto ggtern in R] (http://askubuntu.com/questions/608519/how-to- install-ggtern-package-in-r) – Dante

risposta

1

coord_trans non fa quello che sembra pensarlo. Trasformerà le coordinate xey di un grafico che è già 2D, ma hai dati 3D.

Basta trasformare i dati da soli e quindi tracciarla:

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() 

Si noti che ho riscritto le funzioni di trasformazione per essere più R-like. Inoltre, non dovresti passare espressioni come x = c(x1,x2,x3) all'interno di aes(). Si mappa una singola variabile nel frame dei dati per una singola estetica.

3

La funzione ternaryplot nel pacchetto VCD fa un bel lavoro di rendere diagramma ternario classiche da dati non normalizzata:

require(vcd) 
#ternaryplot takes matrices but not data frames 
xM <- as.matrix(x) 
ternaryplot(xM) 

enter image description here

12

Come mmann1123 evidenziato, utilizzando ggtern, quanto segue può essere ottenuto:

Output

Con la seguente semplice codeblock:

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(x1,x2,x3)) + 
    geom_point(fill="red",shape=21,size=4) + 
    theme_tern_bw() 
0

Il pacchetto R Ternary produce ternario trame da matrici e data.frames utilizzando il funzioni grafiche standard.

Ternary plot created with R package Ternary

La trama di cui sopra è creato con:

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) 
) 
TernaryPlot() 
TernaryPoints(x, col='red') 
Problemi correlati