在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()
编辑,设置名称和传奇的标签
# 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"))
这可能是值得加入这个例子在上面链接,以及问题的答案ggplot。对于有12个upvotes的答案,这不是'ggplot'代码的一个很好的例子。 – joran
好点。 @Fabs有点不幸绊倒了一个大范围的例子。 – Henrik
谢谢!但我认为现在这个例子不适合我...(或者我不明白这个例子,并且对此感到抱歉)......我将编辑我的问题并展示我的例子的一部分......也许有一个简单的方法来做我想做的事情....再次感谢! – Fabs