如何在ggplot的嵌套循环中为跨图中的因子分配相同的颜色?

K. *_*rya 5 plot r subset nested-loops ggplot2

我正在尝试使用 scale_fill_manual 将相应的颜色分配给嵌套 for 循环中许多图中的因子。然而,结果图最终都是黑色的。

我的整体循环如下:

for(i in seq(from=0, to=100, by=10)){
   for{j in seq(from=0, to=100, by=10)){
       print(ggplot(aes(x , y), data = df)+
        geom_point(inherit.aes = FALSE,data = subset(df,factor_x==i&factor_y==j), aes(x, y, size=point,color=Group))+
        theme_bw()}}
Run Code Online (Sandbox Code Playgroud)

我正在尝试为“分组”中的每个因素分配其自己绘制的一致颜色。我试过使用:

col<-colorRampPalette(brewer.pal(9,"Set1"))(16)
Run Code Online (Sandbox Code Playgroud)

然后我将每种颜色分配给“组”中的特定因素。

但是,在嵌套循环中使用 scale manual 时,因子根本没有颜色。

for(i in seq(from=0, to=100, by=10)){
   for{j in seq(from=0, to=100, by=10)){
       print(ggplot(aes(x , y), data = df)+
        geom_point(inherit.aes = FALSE,data = subset(df,factor_x==i&factor_y==j), aes(x, y, size=point))+
        theme_bw()+scale_fill_manual(values=col)}}
Run Code Online (Sandbox Code Playgroud)

如何在循环中生成的许多图中为“组”中的分类值集成配色方案?

eip*_*i10 7

这个想法是创建一个命名的颜色向量,将所需的颜色分配给您在绘图中用于颜色(或填充)美学的因子变量的每个潜在级别。然后在scale_color_manual(或scale_fill_manual) 中使用该颜色向量来设置绘图颜色。这将为所需的因子水平分配所需的颜色,无论给定的因子水平是否存在于用于给定图的特定数据框中。

这是一个简单的例子:

library(ggplot2)

# Plotting function
pfunc = function(data, x, y, col_var, color_vec, drop=TRUE) {
  ggplot(data, aes_string(x, y, colour=col_var)) +
    geom_point(size=3) +
    scale_colour_manual(values=color_vec, drop=drop)
}
Run Code Online (Sandbox Code Playgroud)

现在iris使用整个数据框和数据的一个子集运行带有内置数据框的函数。

# Named vector giving desired color for each Species
col = setNames(c("green","red","blue"), levels(iris$Species))

pfunc(iris, "Petal.Width", "Petal.Length", "Species", col)
pfunc(subset(iris, Species=="versicolor"), 
      "Petal.Width", "Petal.Length", "Species", col)
pfunc(subset(iris, Species=="versicolor"), 
      "Petal.Width", "Petal.Length", "Species", col, drop=FALSE)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

或者使用diamonds数据框:

n = length(levels(diamonds$color))
col = setNames(hcl(seq(15,375,length=n+1)[1:n], 100, 65), levels(diamonds$color))

set.seed(2)
dat = diamonds[sample(1:nrow(diamonds), 200), ]

pfunc(dat, "carat", "price", "color", col)
pfunc(subset(dat, color %in% c("D","G")), "carat", "price", "color", col)
pfunc(subset(dat, color %in% c("G","I")), "carat", "price", "color", col)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明