r - 如果矩阵而不是数据框,则 R 绘图中的标记点不打印

标签 r plot label

好吧...愚蠢的模拟数据...按姓名首字母、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 本质上如此不友好是因为它的创建是为了在没有商业利益的情况下完成任务,还是因为它下面有太多层使其笨重? (我离题了 - 并不是要开始对话......)

最佳答案

将来您应该提供您的数据以防出现问题。但我认为情况并非如此。生成绘图后,您可以使用更简单的 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

关于r - 如果矩阵而不是数据框,则 R 绘图中的标记点不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30135757/

相关文章:

r - 将多个 ggplot2 绘图与网格对齐

plot - ipython notebook 中的动画图

Delphi:更改链接TLinkLabel的字体

r - 将 bool 指标列转换为单因子列

r - 求多边形外接圆的半径

python - 递归动画 matplotlib

r - 如何绘制按因子分组的数据,但不是作为箱线图

google-maps-api-3 - 如何在 Google Maps V3 中永久显示标记的标签/标题?

javascript - 多线图标签 - D3.js

r - 如何在 R 的 for 循环中顺序添加条件