Reputation: 2956
I have two dataframes Data1 and Data2. Data1 has Date and Price and Ticker. Data2 has date and Volume and Ticker.The two dataframes are different length. That is, the Dates cannot be matched one-to-one so I can't put them into one dataframe without interpolating.
I want to plot Price versus Date and Volume versus date on the same plot which I guess means different layers and different scales. But I also want to facet on ticker.
How do I do this in ggplot2 without resorting to for loops?
Upvotes: 0
Views: 1134
Reputation: 2956
Ok, here is my answer using my idea expressed above in comment.
ticks=c('JNJ','IBM','MSFT','GOOG','CAT','BAC')
N1=100
N2=200
Data1=data.frame(x=runif(N1),y=cumsum(runif(N1)),
ticks=sample(ticks,N1,replace=T), tag='data1')
Data2=data.frame(x=runif(N2),y=cumsum(runif(N2)),
ticks=sample(ticks,N2,replace=T),tag='data2')
D=rbind(Data1,Data2)
ggplot(data=D,aes(x=x,y=y,colour=tag))+geom_line()+facet_wrap(~ticks)
That works ok but I still needed to rename the variables.
Upvotes: 0
Reputation: 1616
Seeing your data would help, but I think this should work. I made the two data sets different colors, but doing things this way does not automatically produce a legend and the y-axis is labeled with only the first variable.
ggplot(Data1, aes(Date, Price)) + facet_wrap(~ Ticker) + geom_line(color="blue") + geom_line(data=Data2, aes(date, Volume), color="red")
Upvotes: 1