2014-04-14 9 views
6

Sono così abituato a fare questo in ggplot2 che sto avendo un momento difficile capire come specificare i valori alfa usando la grafica di base R, mentre l'argomento col = in plot() viene utilizzato per assegnare un tipo di colore a una variabile categoriale.Cambiare i valori alfa in R {grafica} mentre l'argomento colore è usato

Utilizzando il set di dati dell'iride (anche se in questo contesto, in realtà non ha senso perché avremmo bisogno di modificare i valori alfa)

data(iris) 
library(ggplot2) 
g <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour=Species), alpha=0.5) #desired plot 

plot(iris$Sepal.Length, iris$Petal.Length, col=iris$Species) #attempt in base graphics 

Che dire di mappatura un'altra variabile per il valore alfa utilizzando {grafica }? Per esempio in ggplot2:

g2 <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour=Species, alpha=Petal.Width)) 

Ogni aiuto è apprezzato!

risposta

8

Regolazione alfa è abbastanza facile con adjustcolor funzione:

COL <- adjustcolor(c("red", "blue", "darkgreen")[iris$Species], alpha.f = 0.5) 
plot(iris$Sepal.Length, iris$Petal.Length, col = COL, pch = 19, cex = 1.5) #attempt in base graphics 

enter image description here

mappatura alpha alla variabile richiede un po 'di più l'hacking:

# Allocate Petal.Length to 7 length categories 
seq.pl <- seq(min(iris$Petal.Length)-0.1,max(iris$Petal.Length)+0.1, length.out = 7) 

# Define number of alpha groups needed to fill these 
cats <- nlevels(cut(iris$Petal.Length, breaks = seq.pl)) 

# Create alpha mapping 
alpha.mapping <- as.numeric(as.character(cut(iris$Petal.Length, breaks = seq.pl, labels = seq(100,255,len = cats)))) 

# Allocate species by colors 
COLS <- as.data.frame(col2rgb(c("red", "blue", "darkgreen")[iris$Species])) 

# Combine colors and alpha mapping 
COL <- unlist(lapply(1:ncol(COLS), function(i) { 
    rgb(red = COLS[1,i], green = COLS[2,i], blue = COLS[3,i], alpha = alpha.mapping[i], maxColorValue = 255) 
    })) 

# Plot 
plot(iris$Sepal.Length, iris$Petal.Length, col = COL, pch = 19, cex = 1.5) 

enter image description here

+0

Credo che questo sarebbe stato anche utile se ho trovato in anticipo! http://lamages.blogspot.ca/2013/04/how-to-change-alpha-value-of-colours-in.html – user3389288

3

Si può provare a utilizzare la funzione

adjustcolor Ad esempio:

getColWithAlpha <- function(colLevel, alphaLevel) 
{ 
    maxAlpha <- max(alphaLevel) 
    cols <- rainbow(length(levels(colLevel))) 
    res <- cols[colLevel] 
    sapply(seq(along.with=res), function(i) adjustcolor(res[i], alphaLevel[i]/maxAlpha)) 
} 

plot(iris$Sepal.Length, iris$Petal.Length, 
     col = getColWithAlpha(iris$Species, iris$Petal.Width), pch = 20) 

Speranza che aiuta,

alex

Problemi correlati