在R中用不同的x轴绘制2条线

时间:2014-04-29 17:34:37

标签: r

我有2个数据帧x和y,我必须合并。

然后我想绘制2行:

第1行=来自x数据框的“vol” 第2行=来自y数据框的“vol”

两条线都应该在x轴上“打击”。

我遇到了错误。我认为这是因为x轴不一样。

你能帮忙吗?

我真的很想使用ggplot。

以下是我可以运行的代码:

x<- data.frame(strike= c(1,2,2.5,7), term= c("H15"), Vol = c(6,7,8,9), file="a")
x
y<- data.frame(strike= c(1,2,2.75,7), term=c("H15"), Vol = c(7,9,10,12),file="b")
y
main<- merge(x,y, by = "strike", all= TRUE)
main

strikes<- factor(main$strike,levels=c(main$strike),ordered=TRUE)
strikes

stacked <- data.frame(time=strikes, value =c(c(x$Vol), c(y$Vol)) , variable =   rep(c("a","b"), each=NROW(x[,1])))  
stacked

MyPlot<- ggplot(stacked, aes( x = time,  y=value, colour=variable, group= variable)  )   +   geom_line()  
MyPlot

1 个答案:

答案 0 :(得分:2)

您可以使用reshape2gpplot2

执行此操作

冷杉让你的数据融化:

library(reshape2)
x.melt<-melt(x[,c("strike", "Vol")], id="strike")
y.melt<-melt(y[,c("strike", "Vol")], id="strike")
x.melt[, "variable"] <-"Vol.x"
y.melt[, "variable"] <-"Vol.y"
data <- rbind(x.melt, y.melt)

有了这个,我们有:

  strike variable value
1   1.00    Vol.x     6
2   2.00    Vol.x     7
3   2.50    Vol.x     8
4   7.00    Vol.x     9
5   1.00    Vol.y     7
6   2.00    Vol.y     9
7   2.75    Vol.y    10
8   7.00    Vol.y    12

不,我们可以将其用于gpplot2

library(ggplot2)
ggplot(data, aes(x=strike,  y=value, colour=variable))   +  geom_point()+ geom_line() 

结果:

enter image description here