gpt4 book ai didi

r - 在ggplot中混合颜色和填充美学

转载 作者:行者123 更新时间:2023-12-01 08:14:21 35 4
gpt4 key购买 nike

我想知道是否有可能根据分类变量更改填充主颜色

这是一个可重现的例子

df = data.frame(x = c(rnorm(10, mean = 0),
rnorm(10, mean = 3)),
y = c(rnorm(10, mean = 0),
rnorm(10, mean = 3)),
grp = c(rep('a', times = 10),
rep('b', times = 10)),
val = rep(1:10, times = 2))

ggplot(data = df,
aes(x = x,
y = y)) +
geom_point(pch = 21,
aes(color = grp,
fill = val,
size = val))

And this is the output

当然,根据变量grp,很容易改变圆圈的颜色/形状,但我希望a组为红色阴影,b组为蓝色阴影。
我也想过用facets,但是不知道两个面板的填充渐变能不能改。

任何人都知道如果没有 gridExtra 是否可以做到?

谢谢!

最佳答案

我认为有两种方法可以做到这一点。第一个是使用 alpha您的审美 val柱子。这是实现目标的快速简便的方法,但可能不是您想要的:

ggplot(data = df,
aes(x = x,
y = y)) +
geom_point(pch = 21,
aes(alpha=val,
fill = grp,
size = val)) + theme_minimal()

enter image description here

第二种方法是做类似于这篇文章的事情: Vary the color gradient on a scatter plot created with ggplot2 .我稍微编辑了代码,所以它的范围不是从白色到您感兴趣的颜色,而是从较浅的颜色到较深的颜色。这需要一些工作并使用 scale_fill_identity函数基本上采用具有您想要的颜色的变量并将它们直接映射到每个点(因此它不进行任何缩放)。

这段代码是:
#Rescale val to [0,1]
df$scaled_val <- rescale(df$val)
low_cols <- c("firebrick1","deepskyblue")
high_cols <- c("darkred","deepskyblue4")

df$col <- ddply(df, .(grp), function(x)
data.frame(col=apply(colorRamp(c(low_cols[as.numeric(x$grp)[1]], high_cols[as.numeric(x$grp)[1]]))(x$scaled_val),
1,function(x)rgb(x[1],x[2],x[3], max=255)))
)$col
df

ggplot(data = df,
aes(x = x,
y = y)) +
geom_point(pch = 21,
aes(
fill = col,
size = val)) + theme_minimal() +scale_fill_identity()

enter image description here

关于r - 在ggplot中混合颜色和填充美学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894381/

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