在 R 绘图中标记点,如果使用矩阵而不是数据框,则无法打印

3

好的... 一些虚拟数据... 学科名称用缩写表示,SAT考试成绩和后来的生活收入以千美元为单位。这些条目已经被缩放和居中处理,并且看起来像这样:

names <- c("TK","AJ","CC", "ZX", "FF", "OK", "CT", "AF", "MF", "ED", "JV", "LK", "AS", "JS", "SR", "CF", "MH", "BM")
SAT <- c(1345, 1566, 1600, 1002, 1008, 999, 1599, 1488, 950, 1567, 1497, 1300, 1588, 1443, 1138, 1557, 1478, 1600)
income <- c(150e3, 250e3, 300e3, 100e3, 110e3, 199e3, 240e3, 255e3, 75e3, 299e3, 300e3, 125e3, 400e3, 120e3, 86e3, 225e3, 210e3, 60e3)

dat <- cbind(SAT, income)
row.names(dat) <- names
dat <- scale(dat, scale = T, center = T)

plot(income ~ SAT, col=as.factor(rownames(dat)), pch= 19, xlim = c(-2.5,2.5), ylim=c(-2.5,2.5), data = dat)
abline(v=0,h=0, col = "dark gray")
text(x=dat$SAT, y=dat$income, rownames(dat), pos=3, cex = 0.5)

...结果是正确的,除了缺失的标签。这是图表和错误消息:

enter image description here dat$SAT的错误:$运算符对于原子向量无效

然而,在我做出一些激烈的举动之前,我发现只有在绘图之前对代码进行微小的修改才会改变一切:

dat <- as.data.frame(dat)

好的,现在开始...

dat <- cbind(SAT, income)
row.names(dat) <- names
dat <- scale(dat, scale = T, center = T)

dat <- as.data.frame(dat)
plot(income ~ SAT, col=as.factor(rownames(dat)), pch= 19, xlim = c(-2.5,2.5), ylim=c(-2.5,2.5), data = dat)
abline(v=0,h=0, col = "dark gray")
text(x=dat$SAT, y=dat$income, rownames(dat), pos=3, cex = 0.5)

enter image description here

所以,我想问题在于在给点标签前要确保我们正在处理数据框架。R语言是否因为没有商业利益而 intrinsically 不友好?还是因为它底层有太多层次而使其笨重不堪?(我扯远了——并不想开启一场讨论……)

1个回答

4

将来,您应该提供数据,以防万一可能存在问题。但我不认为这是问题所在。在生成您的图表后,您可以使用更简单的text()函数完成标签:

names <- c(
  "TK","AJ","CC", "ZX", "FF", "OK", "CT", "AF", "MF", 
  "ED", "JV", "LK", "AS", "JS", "SR", "CF", "MH", "BM"
)
SAT <- c(
  1345, 1566, 1600, 1002, 1008, 999, 1599, 1488, 950, 
  1567, 1497, 1300, 1588, 1443, 1138, 1557, 1478, 1600
)
income <- c(150e3, 250e3, 300e3, 100e3, 110e3, 199e3, 240e3, 
  255e3, 75e3, 299e3, 300e3, 125e3, 400e3, 120e3, 86e3, 
  225e3, 210e3, 60e3
)

dat <- data.frame(SAT, income)
dat <- scale(dat, scale = T, center = T)

##  Note the conversion here back to a data.frame object, since scale()
##    converts to a matrix object:
dat <- as.data.frame(dat)
row.names(dat) <- names

plot(income ~ SAT, col=as.factor(rownames(dat)),
     pch= 19, xlim = c(-2.5,2.5), ylim=c(-2.5,2.5),
     data = dat)

##  Plot text labels above (pos=3) point locations:
text(x=dat$SAT, y=dat$income, row.names(dat), pos=3, cex=0.5) 

enter image description here


谢谢。我尝试了很多方法,包括你建议的,但直到今天早上才意识到数据框架配置的问题。我已经相应地更新了我的帖子。请随意修改您的答案,以便我可以将其标记为“已接受”。 - Antoni Parellada
我已添加完整数据并编辑了代码以反映您在上面所做的更改,以显示缩放和转换为“data.frame”对象。希望这有所帮助! - Forrest R. Stevens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接