3

I am trying to plot two vectors with different values, but equal length on the same graph as follows:

a<-23.33:52.33
b<-33.33:62.33
days<-1:30

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

      a   b    days
 1    23.33 33.33    1
 2    24.33 34.33    2
 3    25.33 35.33    3
 4    26.33 36.33    4
 5    27.33 37.33    5
 etc..

I am trying to use ggplot2 to plot x and y on the x-axis and the days on the y-axis. However, I can't figure out how to do it. I am able to plot them individually and combine the graphs, but I want just one graph with both a and b vectors (different colors) on x-axis and number of days on y-axis.

What I have so far:

X<-ggplot(df, aes(x=a,y=days)) + geom_line(color="red")
Y<-ggplot(df, aes(x=b,y=days)) + geom_line(color="blue")

Is there any way to define the x-axis for both a and b vectors? I have also tried using the melt long function, but got stuck afterwards.

Any help is much appreciated. Thank you

2
  • 1
    ggplot(df) + geom_line(aes(a,days),colour="red") + geom_line(aes(b,days),colour="blue") Commented Sep 1, 2013 at 16:41
  • That works great. Thank you. still getting around to using ggplot. Commented Sep 1, 2013 at 17:00

2 Answers 2

1

I think the best way to do it is via a the approach of melting the data (as you have mentioned). Especially if you are going to add more vectors. This is the code

library(reshape2)
library(ggplot2)

a<-23:52
b<-33:62
days<-1:30

df<-data.frame(x=a,y=b,days)
df_molten=melt(df,id.vars="days")

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

You can also change the colors manually via scale_color_manual.

Sign up to request clarification or add additional context in comments.

Comments

0

A simpler solution is to use only ggplot. The following code will work in your case

a<-23.33:52.33
b<-33.33:62.33
days<-1:30

df<-data.frame(a,b,days) 

ggplot(data = df)+
geom_line(aes(x = df$days,y = df$a), color = "blue")+
geom_line(aes(x = df$days,y = df$b), color = "red")

I added the colors, you might want to use them to differentiate between your variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.