I try to plot multiple lines in single plot as follow:
y <- matrix(rnorm(100), 10, 10)
m <- qplot(NULL)
for(i in 1:10) {
m <- m + geom_line(aes(x = 1:10, y = y[,i]))
}
plot(m)
However, it seems that qplot
will parse m
during plot(m)
where i
is 10
, so plot(m)
produces single line only.
What I expect to see is similar to:
plot(1,1,type='n', ylim=range(y), xlim=c(1,10))
for(i in 1:10) {
lines(1:10, y[,i])
}
which should contain 10 different lines.
Is there ggplot2
way to do this?
In this method to create a ggplot with multiple lines, the user needs to first install and import the reshape2 package in the R console and call the melt() function with the required parameters to format the given data to long data form and then use the ggplot() function to plot the ggplot of the formatted data.
You can create a scatter plot in R with multiple variables, known as pairwise scatter plot or scatterplot matrix, with the pairs function. In addition, in case your dataset contains a factor variable, you can specify the variable in the col argument as follows to plot the groups with different color.
The R function abline() can be used to add vertical, horizontal or regression lines to a graph. A simplified format of the abline() function is : abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)
Instead of ruuning a loop, you should do this the ggplot2 way. ggplot2 wants the data in the long-format (you can convert it with reshape2::melt()). Then split the lines via a column (here Var2).
y <- matrix(rnorm(100), 10, 10)
require(reshape2)
y_m <- melt(y)
require(ggplot2)
ggplot() +
geom_line(data = y_m, aes(x = Var1, y = value, group = Var2))
The way EDi proposed is the best way. If you you still want to use a for
loop you need to use the for loop to generate the data frame.
like below:
# make the data
> df <- NULL
> for(i in 1:10){
+ temp_df <- data.frame(x=1:10, y=y[,i], col=rep(i:i, each=10))
+ df <- rbind(df,temp_df)}
> ggplot(df,aes(x=x,y=y,group=col,colour=factor(col))) + geom_line() # plot data
This outputs:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With