Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot data from lists in R

Tags:

list

plot

r

here is the problem. I have two lists of vectors, sorted (i hope, but i thing i can sort them if they arent) where ith vector in first list has as many numbers as ith vector in the second list. I just want to plot them. But I fear R cant plot elements of lists. Any ideas how to fix that? Thx a lot. Here is the code i tried.

a<-c(2,1,5)
b<-c(2,2,2)
f<-c(4)
g<-c(1)
k<-list(a,f)
l<-list(b,g)
for(i in 1:2){
plot(l[i],k[i])}

and the issue is

Error in xy.coords(x, y, xlabel, ylabel, log) : (list) object cannot be coerced to type 'double'

like image 202
Bobesh Avatar asked Sep 30 '15 19:09

Bobesh


People also ask

How do I plot a Dataframe from a list in R?

The geom_line() method is used to plot the data in the form of lines. We will be using the lapply() method in base R which applies a function, which may be user defined or pre-defined to the input data object. Parameter : list-of-data-frame – The list of dataframes formed.

Can you make a list of plots in R?

List of plots using map() function in purrr. Using the results from split() function, we can create a list of plots, ggplot objects, using map() function in purrr R package. In this example, map() makes a scatter plot for each species.


2 Answers

The best way to do it is to avoid the for-loop and unlist the lists in order to plot them.

This is a way using unlist:

plot(unlist(l),unlist(k))

enter image description here

The way to do it with a for-loop would be the following:

for (i in 1:2) {
  par(new=T)
  plot(l[[i]], k[[i]], xlim=c(0,2), ylim=c(0,5))
}

But it is totally unnecessary as you can get the same result simply by unlisting. You would also have to use par(new=T) so that the second (or any other) plot won't overwrite the previous ones and you would have to specify x and y limits so that the two plots would have the same scales. Also, you would have to use double square brackets [[]] as @HubertL mentions in his answer to access the lists. The result would be the same as above (with the labels in a bolder format since labels would be plotted twice on top of each other).

like image 69
LyzandeR Avatar answered Oct 05 '22 16:10

LyzandeR


You can try to use double brackets[[]]:

plot(l[[i]],k[[i]])
like image 32
HubertL Avatar answered Oct 05 '22 15:10

HubertL