Как сделать следующее в R? - программирование
Подтвердить что ты не робот

Как сделать следующее в R?

Я новичок в заговоре в R, поэтому я прошу вас о помощи. Скажем, у меня есть следующая матрица.

mat1 <- matrix(seq(1:6), 3)
dimnames(mat1)[[2]] <- c("x", "y")
dimnames(mat1)[[1]] <- c("a", "b", "c")
mat1
  x y
a 1 4
b 2 5
c 3 6

Я хочу построить это, где ось x содержит каждое rowname (a, b, c), а ось y - значение каждого rowname (a = 1 и 4, b = 2 и 5, c = 3 и 6). Любая помощь будет оценена!

|     o
|   o x
| o x
| x
|_______
  a b c
4b9b3361

Ответ 1

Здесь один способ использования базовой графики:

plot(c(1,3),range(mat1),type = "n",xaxt ="n")
points(1:3,mat1[,2])
points(1:3,mat1[,1],pch = "x")
axis(1,at = 1:3,labels = rownames(mat1))

enter image description here

Отредактировано для включения другого символа графика

Ответ 2

matplot() был предназначен для данных только в этом формате:

matplot(y = mat1, pch = c(4,1), col = "black", xaxt ="n",
        xlab = "x-axis", ylab = "y-axis")
axis(1, at = 1:nrow(mat1), labels = rownames(mat1))             ## Thanks, Joran

enter image description here

Ответ 3

Наконец, решетчатое решение

library(lattice)
dfmat <- as.data.frame(mat1)
xyplot( x + y ~ factor(rownames(dfmat)), data=dfmat, pch=c(4,1), cex=2)

enter image description here

Ответ 4

Вы можете сделать это в базовой графике, но если вы собираетесь использовать R гораздо больше, чем это, я думаю, что стоит познакомиться с пакетом ggplot2. Обратите внимание, что ggplot2 принимает только кадры данных, но часто бывает полезно хранить данные в кадрах данных, а не в матрицах.

d <- as.data.frame(mat1) #convert to a data frame
d$cat <- rownames(d) #add the 'cat' column
dm <- melt(d, id.vars)
dm #look at dm to get an idea of what melt is doing

require(ggplot2)
ggplot(dm, aes(x=cat, y=value, shape=variable)) #define the data the plot will use, and the 'aesthetics' (i.e., how the data are mapped to visible space)
  + geom_point() #represent the data with points

enter image description here