2014-11-08 128 views
0

我在x軸上有一系列點,每個點在y軸上有兩個點。ggplot2中具有相同自變量的多條曲線

x<-seq(8.5,10,by=0.1) 
y<-c(0.9990276914, 0.9973015358, 0.9931704801, 0.9842176288, 0.9666471511, 0.9354201700, 0.8851624615, 0.8119131899, 0.7152339504, 0.5996777045, 0.4745986612, 0.3519940258, 0.2431610835, 0.1556738744, 0.0919857178, 0.0500000000, 0.0249347645, 0.0113838852, 0.0047497169, 0.0018085048, 0.0006276833) 
y1<-c(9.999998e-01,9.999980e-01,9.999847e-01,9.999011e-01,9.994707e-01,9.976528e-01,9.913453e-01, 9.733730e-01, 9.313130e-01, 8.504646e-01, 7.228116e-01, 5.572501e-01,3.808638e-01,2.264990e-01, 1.155286e-01, 5.000000e-02, 1.821625e-02, 5.554031e-03, 1.410980e-03, 2.976926e-04, 5.203069e-05) 

我現在想在ggplot2中創建兩條曲線。這很容易在R中以正常方式完成。結果在下面的圖中。然而,我不確定如何在ggplot2中做到這一點。對於只有一條曲線,我可以使用

library(ggplot2) 
p<-qplot(x,y,geom="line") 

請問您能幫我概括一下上面的內容嗎?任何幫助非常感謝,謝謝。 enter image description here

+0

有在'geom_line一些例子?使用reshape2包一個可能的解決' – rawr 2014-11-08 21:43:04

回答

1

由於@Roland也指出,首先應該解決的x長度。

library(reshape2) 
library(ggplot2) 

x<-seq(8.5,10,length.out = 21) 
y<-c(0.9990276914, 0.9973015358, 0.9931704801, 0.9842176288, 0.9666471511, 0.9354201700, 0.8851624615, 0.8119131899, 0.7152339504, 0.5996777045, 0.4745986612, 0.3519940258, 0.2431610835, 0.1556738744, 0.0919857178, 0.0500000000, 0.0249347645, 0.0113838852, 0.0047497169, 0.0018085048, 0.0006276833) 
y1<-c(9.999998e-01,9.999980e-01,9.999847e-01,9.999011e-01,9.994707e-01,9.976528e-01,9.913453e-01, 9.733730e-01, 9.313130e-01, 8.504646e-01, 7.228116e-01, 5.572501e-01,3.808638e-01,2.264990e-01, 1.155286e-01, 5.000000e-02, 1.821625e-02, 5.554031e-03, 1.410980e-03, 2.976926e-04, 5.203069e-05) 

df <- data.frame(x, y, y1) 

df <- melt(df, id.var='x') 


ggplot(df, aes(x = x, y = value, color = variable))+geom_line() 

enter image description here

編輯:: 更改線型和圖例:

g <- ggplot(df, aes(x = x, y = value, color = variable, linetype=variable)) + geom_line() 

g <- g + scale_linetype_discrete(name="Custom legend name", 
           labels=c("Curve1", "Curve2")) 

g <- g + guides(color=FALSE) 

print(g) 

enter image description here

+0

非常感謝。你能否也請告訴我如何改變線條,使一個是正常的,另一個是點綴的?當然還有傳說。 – JohnK 2014-11-08 21:57:30

+0

@JohnK查看編輯答案。 – Arpi 2014-11-08 22:13:52

2

請注意,您的x和y值的長度不匹配。結合您的數據,並使用一個分組變量:

x<-seq(8.5,10, length.out = 21) 
DF <- data.frame(x=rep(x, 2), y=c(y, y1), g=c(y^0, y1^0*2)) 

library(ggplot2) 
ggplot(DF, aes(x=x, y=y, colour=factor(g), linetype=factor(g))) + 
    geom_line() 
+0

哦,對不起,我錯過了 一個點。感謝您的答覆。 – JohnK 2014-11-08 22:01:39

相關問題