Search code examples
rplotscatter-plot

Plot with different colour variables and average line in R


I have a dataset in R of values in [-1,1] for 5 countries, namely (A,B,C,D,E) as follows:

data <- matrix(runif(n=50, min = -1, max = 1),ncol = 5)
data <- round(data,2)
colnames(data) <-
  c("A", "B", "C", "D", "E")

Then I calculate the average value of each row for all countries with the following:

aver <- as.matrix(rowMeans(data))
rownames(aver) <- c("X1","X2","X3","X4","X5","X6","X7","X8","X9","X10")

I want to create a plot with the observations with each country (column) to have different colors and the aver line to be included. I am using the following but can not make it properly work.

plot(c(data),col=c("red","yellow","green","blue","black"))
lines(aver)

The final result must look like this but with colored observations included:enter image description here

How can I do that??


Solution

  • Maybe you want something like this:

    matplot(as.data.frame(data),col=c("red","yellow","green","blue","black"), pch=16, ylab = "")
    lines(aver)
    

    Output:

    enter image description here

    Add this for legend:

    legend("bottomright", legend = colnames(data)[1:5], col=c("red","yellow","green","blue","black"), pch = 16)
    

    Output:

    enter image description here