1

I am a newbie to R and therefore this maybe "easy" for the R community. I have a data set with one x vector and serval (in this case 8) correspondig y vectors (matrix). I wanted to plot them in one graph with different line colors. Here is what I tried:

df = data.frame(x=x, y = matrix(nrow = length(x), ncol = 8))

mat=matrix(nrow = length(x), ncol = 8)

gp<-ggplot(df,aes(x,mat[,1], group_indices(mat))) +geom_line(size=1) + 
  xlab("Voltage") + ylab("Current") + scale_y_log10() + ggtitle(paste("IV Curve") ) 

for (i in seq(2,8,1) )
  {
    gp= gp + geom_line(aes(x,y=mat[,i], colour=i),size=1)
  }

But this give me only the first and last data in one graph.

What works is this:

gp= gp + geom_line(aes(x,mat[,2], colour=2),size=1) +
  geom_line(aes(x,mat[,3], colour=3),size=1) +
  geom_line(aes(x,mat[,4], colour=4),size=1) +
  geom_line(aes(x,mat[,5], colour=5),size=1) +
  geom_line(aes(x,mat[,6], colour=6),size=1) +
  geom_line(aes(x,mat[,7], colour=7),size=1) +
  geom_line(aes(x,mat[,8], colour=8),size=1) 

But I want to do it more automatic and simple. I am open for new ideas and I guess I am not good with the different variable types in R. Thanks in advance.

Niklas P.
  • 11
  • 2
  • error in data.frame(x = x, y = matrix(nrow = length(x), ncol = 8)) : objekt 'x' not found. Can you make a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – markus Oct 17 '18 at 09:52

2 Answers2

1

Using the builtin 8 column anscombe dataset as an example try this code.

library(ggplot2)
library(zoo)

x <- 1:nrow(anscombe)
autoplot(zoo(anscombe, x), facet = NULL) +
  xlab("Voltage") + 
  ylab("Current") + 
  scale_y_log10() + 
  ggtitle("IV Curve")

giving:

screenshot

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

melt your data set to have your y variable values in a column and have corresponding variable name associated with them. I have done this using the iris data set if you explore the data set you will understand what I mean.

Once you have the melted data its easy to create the chart

 library(ggplot2)
 ggplot(iris,aes(x = Sepal.Length,y=Sepal.Width,color=Species))+geom_point()+geom_line()

enter image description here

rahul
  • 561
  • 1
  • 5
  • 13