【问题标题】:plot with only horizontal gridlines and labels仅具有水平网格线和标签的绘图
【发布时间】:2019-10-22 00:46:04
【问题描述】:

我有一些条形图

barplot(1:3, axes=FALSE)

我想使用基础 R 添加带有标签的水平网格线。

我得到了第一部分使用

par(xpd = TRUE, mai=c(0.5,1,0.5,0.2))  # to extend lines to the left of plotting area
barplot(1:3, axes=FALSE)               # plotting area
grid(nx=0, ny=3, col="gray")           # horizontal grid lines
barplot(1:3, axes=FALSE, add=TRUE)     # get grid lines into background

但我没有得到左端的标签。也就是说,在网格线的左端,我想要 Y 值,这里是 1 和 2。

【问题讨论】:

  • 我无法发布预期的输出,但在末尾添加了描述。

标签: r plot


【解决方案1】:

?grid 的文档给出了这个问题的解决方案。来自注释部分。

注意

如果需要更多微调,直接使用abline(h = ., v = .)

old_par <- par(xpd = TRUE, mai=c(0.5,1,0.5,0.2)) 

barplot(1:3, axes = FALSE)
abline(h = 1:3, col = "grey", lty = "dotted")
barplot(1:3, axes = FALSE, add = TRUE)
text(x = -0.5, y = 1:3, labels = 1:3)

par(old_par)

要将 y 轴标签放在网格线的末端并自动放置它们,可以定义一个函数。

segmText <- function(x0, x1, y, ...){
  segments(x0 = x0, x1 = x1,
           y0 = y, y1 = y, ...)
  text(x = x0, y = y, labels = y)

}

old_par <- par(xpd = TRUE, mai = c(0.5,1,0.5,0.2))  # to extend lines to the left of plotting area
barplot(1:3, axes = FALSE)
segmText(x0 = -0.5, x1 = 4, y = 1:3, col = "grey", lty = "dotted")
barplot(1:3, axes = FALSE, add = TRUE)
par(old_par)

编辑

一个更简单的解决方案似乎在comment by user d.b

graphics.off()
barplot(1:3, axes = FALSE, col = NA, border = NA)
abline(h = 1:3, col = "grey", lty = "dotted")
barplot(1:3, axes = FALSE, add = TRUE)
axis(2, at = 1:3, labels = 1:3, las = 2, col = NA)

【讨论】:

  • 有没有办法让标签到达网格线的末尾?
  • 有没有办法自动将它们与网格线一起放置?
【解决方案2】:

您可以在sapply() 中使用lines() 并使用mtext()。预先绘制一个空白图。

plot(x=0:4, y=0:4, type="n", axes=FALSE, xlab="", ylab="")
sapply(1:3, function(x) lines(0:4, rep(x, 5), lty=3, col="gray"))
barplot(1:3, axes=FALSE, add=TRUE)
mtext(1:3, side=2, line=0, at=1:3, las=1, adj=0)

您可以通过更改来修剪它,例如line=-1 或与adj 一起玩。

生产

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2011-09-25
    • 2022-08-19
    • 2019-11-03
    • 1970-01-01
    • 2017-05-18
    相关资源
    最近更新 更多