为什么cat和text处理空格不同?

时间:2014-04-17 22:08:38

标签: r graphics

我试图使用text函数在绘图上将一些摘要信息绘制为文本。我不明白的是text解释空格的原因与cat不同。

简单的例子:

spaces <- function(x) paste(rep(" ", x), collapse = "")
vals <- c(1000, 5)
e <- paste0(spaces(3), "val1", spaces(8), "val2\n",
            "v: ", vals[1], spaces(12 - nchar(vals[1])), vals[2])

> cat(e) # Gives exactly the output I want
   val1        val2
v: 1000        5

plot(0, type = "n", bty = "n", xaxt = "n", yaxt = "n", ylab = "", 
     xlab = "", xlim = c(0, 5), ylim = c(0, 5))
text(y = 4, x = 1, labels = e, adj = c(0, 1))

<code>text</code> does not handle the spaces correctly.

如您所见,text不处理与控制台输出相同的空格。我希望事情顺利排列,就像在控制台输出中一样。如何修改对象或对text的调用,以便绘制的版本反映控制台输出?

我也尝试过使用:

spaces <- function(x) paste(rep("\t", x), collapse = "")

1 个答案:

答案 0 :(得分:2)

基于来自@Jongware的非常有用的评论,设置par$family适用于我的目的:

par(family = "mono")
plot(0, type = "n", bty = "n", xaxt = "n", yaxt = "n", ylab = "", 
     xlab = "", xlim = c(0, 5), ylim = c(0, 5))
text(y = 4, x = 1, labels = e, adj = c(0, 1))

enter image description here