2013-09-26 124 views
1

The solution with ggplotthis question对我的数据非常有效。然而,我试图添加一个传说,我试过的一切都不起作用...在同一图中绘制两张图

例如,在上述问题的ggplot示例中,如何添加图例以显示红色曲线是相关的到“海洋”,绿色曲线与“土壤”有关?是的,我想添加我将要定义的文本,并且它与我的data.frame中的任何其他变量都没有关系。

下面的例子是我自己的一些资料...

Rate  Probability  Stats 
1.0e-04 1e-04   891.15 
1.0e-05 1e-04   690 
... 

等(这是大约400行)。我有两个类似于上面的数据框。 所以我的代码是

g <- ggplot(Master1MY, aes(Probability)) 
g <- g + geom_point(aes(y=Master1MY$Stats), colour="red", size=1) 
g <- g + geom_point(aes(y=Transposon1MY$Stats), colour="blue", size=1) 
g + labs(title= "10,000bp and 1MY", x = "Probability", y = "Stats") 

情节看起来像this

我只想要一个红色和蓝色的传奇说“大师”和“转座子”

谢谢!

回答

4

ggplot通常最方便的是保持数据为'长'格式。在这里,我使用reshape2包中的函数melt将数据从宽转换为长格式。根据您指定的不同 thetics(大小,形状,颜色等)的不同,会出现相应的图例。

library(ggplot2) 
library(reshape2) 

# data from the example you were referring to, in a 'wide' format. 
x <- seq(-2, 2, 0.05) 
ocean <- pnorm(x) 
soil <- pnorm(x, 1, 1) 
df <- data.frame(x, ocean, soil) 

# melt the data to a long format 
df2 <- melt(data = df, id.vars = "x") 

# plot, using the aesthetics argument 'colour' 
ggplot(data = df2, aes(x = x, y = value, colour = variable)) + geom_line() 

enter image description here

编辑,设置名称和传奇的标签

# Manually set name of the colour scale and labels for the different colours 
ggplot(data = df2, aes(x = x, y = value, colour = variable)) + 
geom_line() + 
scale_colour_discrete(name = "Type of sample", labels = c("Sea water", "Soil")) 

EDIT 2,下列新的样本数据 转换数据,假设其从您的更新组织,以长格式。再次,我相信如果您将数据保存为长格式,则可以让您的生活更轻松。我将每一步都与我在第一个答案中使用的简单示例数据相关联。请注意,有许多替代方法可以重新排列数据。基于您在更新中提供的数据中的小部分(不可重现)部分,这是一种方法。

# x <- seq(-2, 2, 0.05) 
# Master1MY$Probability 
Probability <- 1:100 

# ocean <- pnorm(x) 
# Master1MY$Stats 
Master1MY <- rnorm(100, mean = 600, sd = 20) 

# soil <- pnorm(x,1,1) 
# Transposon1MY$Stats 
Transposon1MY <- rnorm(100, mean = 100, sd = 10) 

# df <- data.frame(x, ocean, soil) 
df <- data.frame(Probability, Master1MY, Transposon1MY) 

# df2 <- melt(df, id.var = "x") 
df2 <- melt(df, id.var = "Probability") 

# default 
ggplot(data = df2, aes(x = Probability, y = value, col = variable)) + 
    geom_point() 

# change legend name and labels, see previous edit using 'scale_colour_discrete' 

# set manual colours scale using 'scale_colour_manual'. 

ggplot(data = df2, aes(x = Probability, y = value, col = variable)) + 
    geom_point() + 
    scale_colour_manual(values = c("red","blue"), name = "Type of sample", labels = c("Master", "Transposon")) 

enter image description here

+1

这可能是值得加入这个例子在上面链接,以及问题的答案ggplot。对于有12个upvotes的答案,这不是'ggplot'代码的一个很好的例子。 – joran

+0

好点。 @Fabs有点不幸绊倒了一个大范围的例子。 – Henrik

+0

谢谢!但我认为现在这个例子不适合我...(或者我不明白这个例子,并且对此感到抱歉)......我将编辑我的问题并展示我的例子的一部分......也许有一个简单的方法来做我想做的事情....再次感谢! – Fabs

相关问题