如何制作一个有两个标签/图例的ggplot?
示例数据dput():
structure(list(Percentage = c(0, 25, 50, 75, 100, 0, 25, 50,
75, 100), Data = c("group1", "group1", "group1", "group1", "group1",
"group2", "group2", "group2", "group2", "group2"), accuracy_G = c(18.35,
54.53, 68.48, 88.65, 99.96, 18.35, 76.08, 81.63, 88.03, 99.96
), accuracy_1 = c(52.751572327044, 61.5566037735849, 65.8411949685535,
73.8011006289308, 80.6112421383648, 52.751572327044, 64.7209119496855,
67.3054245283019, 70.5090408805032, 80.6112421383648), accuracy_2 = c(52.8498427672956,
61.1930031446541, 66.0966981132076, 73.8404088050314, 80.3360849056604,
52.8498427672956, 64.5538522012579, 67.1678459119497, 70.9217767295598,
80.3360849056604)), .Names = c("Percentage", "Data", "accuracy_G",
"accuracy_1", "accuracy_2"), row.names = c(2L, 4L, 6L, 8L, 10L,
12L, 14L, 16L, 18L, 20L), class = "data.frame")
require(ggplot2)
require(reshape2)
data.melt <- melt(data, id.vars=c("Percentage","Data")) #For plotting with ggplot
现在我可以通过子集来绘制部分图:
data.melt_sub <- subset(data.melt,Data == "group1")
ggplot( data.melt_sub ,aes(x = Percentage,y = value,colour=variable)) + geom_line()
但是,我想在右边有两个标签,一个用于'group1',一个用于'group2'(每个用于创建3行)。对于线条的颜色,我想使用来自酿酒商的palette =“Paired”。这些可以手动调用,但包括scale_fill_brewer(pallete =“Paired”)之类的东西会更好:
require(RColorBrewer)
colours <- brewer.pal(12,"Paired")
答案 0 :(得分:2)
使用完整的融合数据框,然后在color=
内aes()
提供数据和变量之间的互动。然后使用scale_color_manual()
更改图例中的线条颜色和标签。
ggplot( data.melt ,aes(x = Percentage,y = value,colour=interaction(Data,variable))) +
geom_line() + scale_color_manual(values=brewer.pal(6,"Paired"),
labels=rep(c("Group1","Group2"),times=3))