Search code examples
rscatter-plotequivalence

Creating a scatterplot for each value of the first column in an r dataframe


Using the file below, I am trying to creating 2 scatterplots. One scatterplot compares the 2nd and 3rd column when the first column is equal to "coat" and the second scatterplot compares the 2nd and third column when the first column is equal to "hat"

file.txt

clothing,freq,temp
coat,0.3,10
coat,0.9,0
coat,0.1,20
hat,0.5,20
hat,0.3,15
hat,0.1,5

This is the script I have written

script.R

rates = read.csv("file.txt")
for(i in unique(rates[1])){
        plot(unlist(rates[2])[rates[1] == toString(i)],unlist(rates[3])[rates[1] == toString(i)])
}

I receive this error when running it

Error in plot.window(...) : need finite 'xlim' values
Calls: plot -> plot.default -> localWindow -> plot.window
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf
Execution halted

The script works if I replace if I replace "toString(i)" with "hat" but can obviously only make one of the scatterplots.

.

EDIT

I edited my script slightly. It creates a graph for the first iteration through the loop but not for any iteration after the first. This is my script

rates = read.csv("file.txt")
for(i in unique(rates[,1])){
        plot(unlist(rates[2])[rates[1] == toString(i)],unlist(rates[3])[rates[1] == toString(i)])
        file.rename("Rplots.pdf", paste(i,".pdf",sep=""))
}

This is what happens when I execute the script

name@server:/directory> ./script.R 
Warning message:
In file.rename("Rplots.pdf", paste(i, ".pdf", sep = "")) :
  cannot rename file 'Rplots.pdf' to 'hat.pdf', reason 'No such file or directory'
name@server:/directory> ls
coat.pdf  file.txt  script.R*

Solution

  • try this:

    rates = read.table("file.txt",sep=',',header=TRUE)
    
    cloth_type<-unique(rates[,1])   
    
    for (i in 1:length(cloth_type)){
    
        dev.new()
    
        index_included=which(rates[,1]==cloth_type[i])
    
        plot(rates[index_included,2],rates[index_included,3],main=cloth_type[i],
        xlab="freq ", ylab="temp ", pch=19)
    
    }