简体   繁体   中英

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: 在此处输入图像描述

How can I do that??

Maybe you want something like this:

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

Output:

在此处输入图像描述

Add this for legend:

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

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM