gpt4 book ai didi

r - 使用color参数时,更改R {graphics}中的alpha值

转载 作者:行者123 更新时间:2023-12-04 11:25:22 27 4
gpt4 key购买 nike

我非常习惯在ggplot2中执行此操作,以至于很难弄清楚如何使用R基本图形指定alpha值,而plot()中的col =参数用于将颜色类型分配给类别多变的。

使用虹膜数据集(尽管在这种情况下,为什么我们需要更改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

使用{graphics}将另一个变量映射到alpha值怎么办?
例如在ggplot2中:
g2 <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour=Species, alpha=Petal.Width)) 

任何帮助表示赞赏!

最佳答案

使用adjustcolor函数可以很容易地调整Alpha:

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

将alpha映射到变量需要更多的技巧:
# 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)

关于r - 使用color参数时,更改R {graphics}中的alpha值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23062343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com