2012-11-26 41 views
14

我是新来的密谋在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 
+4

顺便说一句,在阅读的链接不错的工作,我给你在一个更好的形式重写你的问题。正如你可以从下面的答案和你的upvotes看到的,它支付了股息! :) – joran

+0

我会得到它的窍门:)谢谢你的指导。 – Stephen

回答

12

这里有一种方法使用基本图形:

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

编辑,包括不同的符标

+0

有什么办法让x轴标签垂直? – Stephen

+0

@ user1854603你的意思是y轴标签?否则,我记下你的意思。 – joran

+1

@ user1854603玩弄'las'参数,像这样:'plot(1:3,las = 1); (1:3,las = 2)'等等直到'las = 4'。 (FWIW,'axis()'也需要一个'las'参数。) –

10

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

+2

...你可以做同样的事情,我用'xaxt'和'axis'来用字母标记x轴。 – joran

+0

@joran - 很好。我补充说,并给你一个帽子提示。 –

+0

所以像'matplot(mat1,xaxt ='n'); (1,at = 1:nrow(mat1),labels = rownames(mat1));' – user295691

3

你能做到这一点的基础图形,但如果你打算用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

6

最后,晶格的解决方案

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

+0

+1对于旧的被忽略的格子 - 我仍然发现它是最好的数据探索工具。 –

+0

@ AriB.Friedman - 对于我的个人教育,格点作为数据探索工具与ggplot相比有什么作用? –

+1

@DrewSteen我发现语法对于切分和切分数据更直观一些。 'ggplot'具有'qplot',但我仍然发现点阵功能可以更快速地添加逐个颜色和逐个分组。此外,带状疱疹也很棒:'dfmat < - data.frame(x = seq(18),y = seq(18),z = rep(seq(3),6),a = runif(18)); xyplot(x + y〜factor(z)| equal.count(a,3),data = dfmat)' –