![](/img/trans.png)
[英]How can I suppress the vertical gridlines in a ggplot2 plot while retaining the x-axis labels?
[英]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)
編輯
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.