我想绘制四行,其中图例标签 AND 颜色由列中的唯一值,“Color_Group”和线型“Line_Type_Group”决定。这是制作数据帧所需的代码,以及数据帧本身。
data <- data.frame("x"=c(1,2,1,2,1,2,1,2),
"y"=1:8,
"Color_Group"=c("A","A","A","A","B","B","C","C"),
"Line_Type_Group"=c(1,1,2,2,2,2,1,1),
"Group"=c("A1","A1","A2","A2","B2","B2","C1","C1"),
stringsAsFactors=F)
> data
x y Color_Group Line_Type_Group Group
1 1 A 1 A1
2 2 A 1 A1
1 3 A 2 A2
2 4 A 2 A2
1 5 B 2 B2
2 6 B 2 B2
1 7 C 1 C1
2 8 C 1 C1
主“组”列是将颜色和线型列粘贴在一起的结果,它表示每行的ID。为了获得一个图例,我最初将颜色和线型属性映射到此“组”列。下面是我想要的情节。
尝试
为简单起见,我正在重新创建数据框,以包含具有文字颜色和线型值的列。
data <- data.frame("x"=c(1,2,1,2,1,2,1,2),
"y"=1:8,"Color_Group"=c("A","A","A","A","B","B","C","C"),
"Color"=c(rep("red",4),"blue","blue","green","green"),
"Line_Type_Group"=c(1,1,2,2,2,2,1,1),
"Line_Type"=c("solid","solid","dashed","dashed","dashed","dashed","solid","solid"),
"Group"=c("A1","A1","A2","A2","B2","B2","C1","C1"),
stringsAsFactors = F)
> data
x y Color_Group Color Line_Type_Group Line_Type Group
1 1 A red 1 solid A1
2 2 A red 1 solid A1
1 3 A red 2 dashed A2
2 4 A red 2 dashed A2
1 5 B blue 2 dashed B2
2 6 B blue 2 dashed B2
1 7 C green 1 solid C1
2 8 C green 1 solid C1
line_type_group <- data$Line_Type
color_group <- data$Color
names(line_type_group) <- data$Group
names(color_group) <- data$Group
labels <- data$Color_Group
names(labels) <- data$Group
#Both attempts at setting labels variable yields plot below
#labels <- c("A","A","B","C")
g <- ggplot(data,aes(x=x,y=y,colour=Group,linetype=Group))+geom_line()
g + scale_colour_manual(name="Legend",values=color_group,labels=labels) +
scale_linetype_manual(name="Legend",values =line_type_group,labels=labels)
答案 0 :(得分:3)
您可以通过在将values
更改为您想要的内容后抑制线型图例,然后使用colour
“手动”设置override.aes
图例中的线型来解决此问题。
ggplot(data,aes(x=x, y=y, colour=Group, linetype=Group))+
geom_line() +
scale_colour_manual(values = color_group, labels = labels) +
scale_linetype_manual(values = line_type_group, guide = "none") +
guides(colour = guide_legend(override.aes = list(linetype = c(1, 2, 2, 1))))
答案 1 :(得分:0)
这几乎可以提供你想要的东西
g <- ggplot(data,aes(x=x,y=y,colour=Group,linetype=Group))+geom_line()
g + scale_colour_manual(name="Legend",values=c("red", "red", "blue", "green"), labels = c("A1", "A2", "B", "C")) +scale_linetype_manual(name="Legend",values=c("solid", "dashed", "dashed", "solid"), labels = c("A1", "A2", "B", "C"))
#
g