gpt4 book ai didi

r - 使用颜色和线型美学属性控制绘图的图例标签

转载 作者:行者123 更新时间:2023-12-04 12:12:01 26 4
gpt4 key购买 nike

我想用图例标签绘制四行 颜色由列中的唯一值“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。为了获得一个图例,我最初将颜色和线型属性映射到此“组”列。下面是我想要的情节。

想要的地块
enter image description here

尝试

为简单起见,我正在重新创建数据框以包含具有文字颜色和线型值的列。
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)

enter image description here

最佳答案

您可以通过在更改 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))))

enter image description here

关于r - 使用颜色和线型美学属性控制绘图的图例标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34318292/

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