簡體   English   中英

plot 只有水平網格線和標簽

[英]plot with only horizontal gridlines and labels

我有一些條形圖

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。

?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 軸標簽放在網格線的末端並自動放置它們,可以定義 function。

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)

編輯

用戶db評論中似乎有一個更簡單的解決方案

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)

您可以在sapply() lines()使用mtext() Plot 預先空 plot。

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來修剪它。

生產

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM