R语言基础图形元素——文本和图例

R语言基础图形元素--文本和图例

简介

图形文本和图例作为一种辅助信息来解释图形,对于图形数据认知至关重要。

1. 文本

图形文本可分为三类,分别是标题,可以通过title()函数添加;图形内部文本,通过text()函数实现;图形周边文本,可以通过mtext()函数实现。

用法

# title
title(main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
      line = NA, outer = FALSE, ...)
# text
text(x, y = NULL, labels = seq_along(x$x), adj = NULL,
     pos = NULL, offset = 0.5, vfont = NULL,
     cex = 1, col = NULL, font = NULL, ...)
# mtext
mtext(text, side = 3, line = 0, outer = FALSE, at = NA,
      adj = NA, padj = NA, cex = NA, col = NA, font = NA, ...)
  • title()函数的前四个参数为主、副、x轴和y轴的标题,line 参数设置一个距离图形边缘的行数,outer 参数表示是否将文本放置在外边界中。
  • text() 函数的参数 labels 就是欲添加的文本;adj 参数与 par() 中说明相同;pos 参数取值整数 1~4 分别表示文本的位置在坐标点的下、左、上、右方,它会覆盖参数 adj 的设置;offset 参数会根据 pos 参数的取值将文本向相应的方向移动一定比例的距离。
  • mtext()函数相关参数参见par()

示例

plot(1:10,1:10,type = "b",col = "red",pch = 19,
     xlim = c(1,12),ylim = c(1,12),
     xlab = "this is x",ylab = "this is y")
text(x = 1:10,y = 2:11,labels =  paste("(",1:10,",",1:10,")",sep = ""),col = rgb(1,seq(0,1,0.1),0))
title(main = "main",sub = "sub")
mtext("dot and line",side = 4,outer = F,col = "purple")

在这里插入图片描述

2. 图例

用法

legend(x, y = NULL, legend, fill = NULL, col = par("col"),
       border = "black", lty, lwd, pch,
       angle = 45, density = NULL, bty = "o", bg = par("bg"),
       box.lwd = par("lwd"), box.lty = par("lty"), box.col = par("fg"),
       pt.bg = NA, cex = 1, pt.cex = cex, pt.lwd = lwd,
       xjust = 0, yjust = 1, x.intersp = 1, y.intersp = 1,
       adj = c(0, 0.5), text.width = NULL, text.col = par("col"),
       text.font = NULL, merge = do.lines && has.pch, trace = FALSE,
       plot = TRUE, ncol = 1, horiz = FALSE, title = NULL,
       inset = 0, xpd, title.col = text.col, title.adj = 0.5,
       seg.len = 2)
  • xy 参数表示legend的位置。
  • legend 参数为字符向量,表示图例中的位置。
  • fill 参数指定一个与图例字符向量对应的颜色向量用以在文本左边绘制一个颜色填充方块。
  • angeldensity 参数的 效果类似于fill参数,只是换成指定角度和密度的阴影线填充方块。
  • bty 参数设置图例框的样式。
  • title 参数设置图例的标题。
  • 其他参数设置图例的细节,不太常用。

示例

文本,线条和图例的综合使用示例。

par(mar = c(5, 5, 5, 5))
plot(0:10, type = "n", xlab = "", ylab = "", xlim = c(0, 12))
grid(col = "gray")
title(main = "example",xlab = "", ylab = "")
mtext("Here is \"side = 4\"", side = 4, line = 1.5)
x <- c(6, 4, 6, 8)
y <- c(8, 5, 2, 5)
s <- c(0, 90, 180, 270)
for (i in 1:length(s)) {
  text(x[i], y[i], sprintf("srt = %d", s[i]),srt = s[i])
}
segments(c(6, 0, 6, 12), c(10, 5, 0, 5), c(0, 6, 12, 6),
         c(5, 0, 5, 10),col = c("purple","steelblue","steelblue","purple"),
         lty = c(2, 1, 1, 2)
)
legend("topright", c("Upper", "Lower"),
       lty = 2:1, cex = 0.8,col = c("purple","steelblue"),
       bty = "n"
)

在这里插入图片描述
R中可以设置极其细微的元素特征,但并不是所有的函数参数都必须细究,掌握核心参数是必然的。掌握R基础绘图函数,可以绘制很多高大上的图形。


##侵权请联系作者删除!

参考书籍

[1] 现代统计图形

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值