1

如何制作具有两个标签/图例的 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 行)。对于线条的颜色,我想使用来自酿酒商的调色板 =“配对”。这些可以手动调用,但包括像 scale_fill_brewer(pallete = "Paired") 这样的东西会更好:

require(RColorBrewer)
colours <- brewer.pal(12,"Paired")
4

1 回答 1

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))

在此处输入图像描述

于 2013-11-12T15:28:01.613 回答