使用多个类别列的所有可用排列为线条着色

Colouring lines by using all available permutations of multiple category columns

我想在 R 中生成一个线图,其中包含多条不同颜色的线,具体取决于 table 中的其他数据。我的数据看起来与此类似:

mydf = data.frame(iteration=c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5), 
            value=runif(20, min=0, max=1),
            category=c("A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B"),
            subcategory=c("x","x","x","x","x","y","y","y","y","y","x","x","x","x","x","y","y","y","y","y"))


 iteration  value   category    subcategory
1   1   0.79813537  A   x
2   2   0.45196396  A   x
3   3   0.28001580  A   x
4   4   0.65997486  A   x
5   5   0.82217320  A   x
6   1   0.33805127  A   y
7   2   0.75842241  A   y
8   3   0.18502805  A   y
9   4   0.75586271  A   y
10  5   0.28269372  A   y
11  1   0.27585682  B   x
12  2   0.45901786  B   x
13  3   0.18962731  B   x
14  4   0.63682207  B   x
15  5   0.89821930  B   x
16  1   0.93757079  B   y
17  2   0.27272290  B   y
18  3   0.20485397  B   y
19  4   0.33647649  B   y
20  5   0.07788958  B   y

现在我想用 ggplot 将四行打印到同一个图中,代表类别和子类别的所有可用组合。我还想为每个组合使用不同的颜色。例如:A.x红色,A.y绿色,B.x蓝色,B.y黄色。

我能想出的最好办法是两种颜色和两种形状来区分线条。

ggplot(data=mydf, 
   aes(x=iteration, y=value, colour=category, shape=subcategory)) + 
 geom_line() + geom_point()

有没有办法为每个可能的类别和子类别排列分配颜色?

谢谢!

(我想展示一些示例图片,但我还没有足够的代表。)

创建一个包含类别和子类别的新变量并将其映射到颜色。

mydf$group <- paste(mydf$category,mydf$subcategory,sep="_")

ggplot(data=mydf, 
   aes(x=iteration, y=value, colour=group)) + 
 geom_line() + geom_point()  +
 scale_color_manual(values = c("red","green","blue","yellow"))