gpt4 book ai didi

r - 在使用 ggplot2 创建的散点图上改变颜色渐变

转载 作者:行者123 更新时间:2023-12-04 10:28:41 25 4
gpt4 key购买 nike

是否可以根据审美改变绘图的颜色渐变?我正在使用类似于下面显示的行的代码生成一个图,并发现在某些情况下,区分各个组并不总是那么容易。例如,在下面的图表中,如果我可以让 A 组点使用白蓝渐变,B 组点使用白红渐变,结果会更容易区分。

data <- data.frame(x=c(1,2,3,4,5,6,1,2,3,4,5,6), 
y=c(1,2,3,4,5,6,1,2,3,4,5,6), grp=c(rep("A",6),rep("B",6)),
dt=c("2010-06-30","2010-05-31","2010-04-30",
"2010-03-31","2010-02-26","2010-01-29","2010-06-30",
"2010-05-31","2010-04-30",
"2010-03-31","2010-02-26","2010-01-29"))
p <- ggplot(data, aes(x,y,color=as.integer(as.Date(data$dt)))) +
geom_jitter(size=4, alpha=0.75, aes(shape=grp)) +
scale_colour_gradient(limits=as.integer(as.Date(c("2010-01-29","2010-06-30"))),
low="white", high="blue") +
scale_shape_discrete(name="") +
opts(legend.position="none")
print(p)

最佳答案

你可以通过在调用 ggplot2 之前自己准备颜色来做到这一点。
这是一个例子:

data$sdt <- rescale(as.numeric(as.Date(data$dt)))  # data scaled [0, 1]
cols <- c("red", "blue") # colour of gradients for each group

# here the color for each value are calculated
data$col <- ddply(data, .(grp), function(x)
data.frame(col=apply(colorRamp(c("white", cols[as.numeric(x$grp)[1]]))(x$sdt),
1,function(x)rgb(x[1],x[2],x[3], max=255)))
)$col

p <- ggplot(data, aes(x,y, shape=grp, colour=col)) +
geom_jitter(size=4, alpha=0.75) +
scale_colour_identity() + # use identity colour scale
scale_shape_discrete(name="") +
opts(legend.position="none")
print(p)

关于r - 在使用 ggplot2 创建的散点图上改变颜色渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5736956/

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