2014-04-14 13 views
6

Tôi rất quen với việc thực hiện điều này trong ggplot2 rằng tôi đang gặp khó khăn trong việc tìm ra cách xác định giá trị alpha bằng đồ họa cơ sở R. đối số col = trong lô() được sử dụng để gán một kiểu màu cho một biến phân loại.Thay đổi giá trị alpha trong R {graphics} trong khi đối số màu được sử dụng

Sử dụng tập dữ liệu iris (mặc dù trong bối cảnh này nó không thực sự có ý nghĩa tại sao chúng ta cần phải thay đổi các giá trị alpha)

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 

gì về lập bản đồ biến khác với giá trị alpha sử dụng {đồ họa }? Ví dụ: trong ggplot2:

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

Mọi trợ giúp đều được đánh giá cao!

Trả lời

8

Điều chỉnh alpha là khá dễ dàng với adjustcolor chức năng:

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 để biến đòi hỏi hack hơn một chút:

# 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

Tôi đoán đây sẽ cũng đã được hữu ích nếu tôi tìm thấy nó trước! http://lamages.blogspot.ca/2013/04/how-to-change-alpha-value-of-colours-in.html – user3389288

3

Bạn có thể thử sử dụng adjustcolor chức năng

Ví dụ:

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) 

Hy vọng nó giúp,

alex

Các vấn đề liên quan