0

I wrote some code that reads some data from a text file, turns it into a matrix and plots each column of the matrix in a separate graph:

#Read data from txt file into table and convert table into matrix
excMatrix = as.matrix(read.table("/Users/Kane/Desktop/Gujarati/Table 1.3.txt", header = TRUE, row.names = 1))

#Plotting function
excPlot = function(x) {
  plot(row.names(excMatrix),x,xlab = "Year", ylab = "Exchange rate (US)", type = "l")
  legend("topright", legend = "something to get column names for legend", pch = 1, col = 1:2, bty = "n")
}

#Plot exchange rates from various countries on seperate graphs
apply(excMatrix, 2, excPlot)

When I run this it makes the correct graphs but I can't figure out how to get the name of the country in the legend i.e. each graph is data for a separate country who's names are the columns of the matrix.

Hopefully that makes sense, any help appreciated.

Kane
  • 914
  • 2
  • 11
  • 27

2 Answers2

0

Some rearranging of your plotting method to loop over the colnames of your matrix will allow this to work. E.g.:

par(mfrow=c(2,2))

excMatrix <- matrix(1:20,ncol=4,dimnames=list(1:5,letters[1:4]))

excPlot = function(x) {
  plot(row.names(excMatrix),excMatrix[,x],xlab = "Year", 
       ylab = "Exchange rate (US)", type = "l")
  legend("topright", 
         legend = x, 
         pch = 1, col = 1:2, bty = "n")
}

lapply(colnames(excMatrix), excPlot)
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • Thanks but I actually need all the plots on separate graphs that's why I set it up that way. But pretty sure I can still use this. – Kane Nov 27 '14 at 04:39
  • @Kane - no problems. I just had the `par()` line included in this example code so that you could see the labels being cycled through. Just remove it and you're good to go. – thelatemail Nov 27 '14 at 05:01
0

I will recommend using par() like what @thelatemail has pointed out. Do check out ?par. It has many parameters such as margins and size for you to play with

If your legend is the same for each plot, you can place your legend() code outside of your excPlot function.

Take a look at this post on stackoverflow :

Common legend for multiple plots in R

Community
  • 1
  • 1
biobirdman
  • 4,060
  • 1
  • 17
  • 15