在同一图中绘制两个图

时间:2013-09-26 20:47:50

标签: r graph ggplot2

The solution with ggplot中的{p> this question对我的数据非常有效。但是,我正在尝试添加一个图例,而我尝试的所有内容都无效......

例如,在上面问题的ggplot示例中,我如何添加图例以显示红色曲线与“Ocean”相关且绿色曲线与“Soil”相关?是的,我想添加我将定义的文本,它与我的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

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

谢谢!

1 个答案:

答案 0 :(得分:5)

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

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

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

# 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

相关问题