使用ggplot()绘制矩阵的第二列和第三列并使用第一列作为x轴的值

时间:2014-01-21 13:04:41

标签: r ggplot2

我有一个矩阵:

a<-c(0.863950263765782, 0.908204672069546, 0.931564826815488, 0.947460752561418, 0.959463328487368, 0.969060077042643, 0.977026409365163, 0.983818665594281,0.989719993426693)

b<-c(0.787029935566084, 0.872407618393809, 0.925762651962245, 0.948331740835959, 0.961947304263652, 0.971489926009247, 0.978878398154957, 0.984799730999978, 0.9899910908)

c<-c("0.1-0.9", "0.2-0.9", "0.3-0.9", "0.4-0.9", "0.5-0.9", "0.6-0.9", "0.7-0.9", "0.8-0.9", "0.9")

e<-cbind(c,a,b)

我想在同一图表上绘制e[,2]e[,3],并使用e[,1]中的相应条目作为x轴的值。

如何使用ggplotplot()

完成此操作
  1. 我尝试melt(e, id.vars=1:1),但我无法以正确的格式获取变量。

1 个答案:

答案 0 :(得分:1)

require(reshape2)
require(ggplot2)
e <- melt(as.data.frame(e), id.vars="c",  measure.vars=c("a", "b"), variable.name="var", value.name="val")
ggplot(e, aes(x=c, y=val, colour=var)) + geom_point()

修改:

奇怪。这段代码......

a<-c("0.863950263765782", "0.908204672069546", "0.931564826815488", "0.947460752561418", "0.959463328487368", "0.969060077042643", "0.977026409365163", "0.983818665594281","0.989719993426693")
b<-c("0.787029935566084", "0.872407618393809", "0.925762651962245", "0.948331740835959", "0.961947304263652", "0.971489926009247", "0.978878398154957", "0.984799730999978", "0.9899910908")
c<-c("0.1-0.9", "0.2-0.9", "0.3-0.9", "0.4-0.9", "0.5-0.9", "0.6-0.9", "0.7-0.9", "0.8-0.9", "0.9")
e<-cbind(c,a,b)
require(reshape2)
require(ggplot2)
e <- melt(as.data.frame(e), id.vars="c",  measure.vars=c("a", "b"), variable.name="var", value.name="val")
ggplot(e, aes(x=c, y=val, colour=var)) + 
  geom_point()

...在我的机器上导致此输出:

enter image description here

这个

ggplot(e, aes(x=c, y=as.numeric(val), colour=var, group=var)) + geom_point() + geom_line()

...导致这个:

enter image description here