Reputation: 11734
With this approach. I have a line plot graph. I want to plot 'two' line plot on the same graph. How can I simply add that data,
The data is in the form
1 5 10
2 8 20
3 9 30
I want to plot the X as column1 and the other two columns along the y axis.
-----
# Commands
2
3 library(ggplot2)
4
5 req <- read.table("stats_quick_sort.dat")
6
7 summary(req)
8
9 xx <- req$V1
10 yy <- req$V2
11
12
13 png('stats_sort_image.png', width=800, height=600)
14 gg <- qplot(xx, yy) + geom_line()
15 print(gg)
16 dev.off()
Upvotes: 1
Views: 3201
Reputation: 69221
Perhaps a slightly more canonical way to use ggplot is to create a long data.frame and map each variable of interest to an aesthetic. This provides an easy way to add legends automagically, etc. This also scales easier than adding individual layers each time you want a new line. Here's an example:
library(ggplot2)
library(reshape2)
#Thanks mathematical coffee for data
dat <- data.frame(xx = sort(runif(20))
, yy = runif(20)
, yy2 = runif(20))
#Melt into long format, using xx as the ID variable
dat.m <- melt(dat, id.vars = "xx")
#What does this look like now?
> head(dat.m,3)
xx variable value
1 0.001895333 yy 0.1240757
2 0.037347893 yy 0.8760621
3 0.086915655 yy 0.4068837
#use ggplot and set the group and colour aesthetic to the variable column. This adds a legend
ggplot(dat.m, aes(xx, value, group = variable, colour = variable)) +
geom_line()
Upvotes: 1
Reputation: 56935
As an aside -- if you provide a reproducible example that demonstrates your problem, it is much easier for us to help you. I'm going to give you a reproducible example as an answer so you see what I mean. It means anyone can copy and paste the code and it'll work (whereas I couldn't copy/paste your code because I don't have stats_quick_sort.dat
).
To plot multiple lines on a plot you just call geom_line
again, feeding in the x
and y
variables to aes
:
# generate some dummy data so this example can be reproduced
xx <- sort(runif(20))
yy <- runif(20)
yy2 <- runif(20)
gg <- qplot(xx, yy) + geom_line() # first line
gg <- gg + geom_line(aes( x=xx, y=yy2 )) # add the second line!
print(gg)
In general, if you want to add other information to your plot that you did not supply in the initial qplot
/ggplot
call, then just feed it in to aes
. You want a line? Use geom_line
. You want new x and y coordinates? Then use geom_line(aes(x= .., y=..))
. And so on.
Upvotes: 2