2014-04-14 3 views
6

Ich bin so in ggplot2, dass es mir sehr schwer, herauszufinden, wie man Alpha-Werte mit R-Basis-Grafiken angeben, während Das Argument col = in plot() wird verwendet, um einer kategorialen Variablen einen Farbtyp zuzuordnen.Ändern der Alpha-Werte in R {Grafik}, während das Argument Farbe verwendet wird

den Irisdatensatz verwenden (obwohl in diesem Zusammenhang ist es nicht wirklich Sinn machen, warum wir die Alpha-Werte ändern müssten)

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 

Was Abbilden einer weitere Variable auf den Alpha-Wert mit {Grafik }? Zum Beispiel in ggplot2:

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

Jede Hilfe ist willkommen!

Antwort

8

Einstellen alpha ist recht einfach mit adjustcolor Funktion:

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

Mapping alpha Variable erfordert ein bisschen mehr 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

Ich denke, dies ist auch nützlich gewesen wäre, wenn ich es vorher gefunden! http://lamages.blogspot.ca/2013/04/how-to-change-alpha-value-of-colours-in.html – user3389288

3

Sie können versuchen, die adjustcolor Funktion

Zum Beispiel zu verwenden:

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) 

Hoffe, dass es hilft,

alex

Verwandte Themen