我想知道如何添加一个字母来引用R中的图形,但不总是改变y和x值。我希望文本始终位于相同的位置(在相同的基线上,并且在x轴上的相对距离相同。
set.seed(1234)
plot(2,3)
text(x = 1.5,y = 4, "A", font = 2 )
plot(rnorm(100))
text(x = 1.5,y = 2, "B", font = 2)
答案 0 :(得分:3)
这就是我过去解决这个问题的方法(基于这些问题:Get margin line locations (mgp) in user coordinates,Get margin line locations in log space):
line2user <- function(line, side) {
lh <- par('cin')[2] * par('cex') * par('lheight')
x_off <- diff(grconvertX(c(0, lh), 'inches', 'npc'))
y_off <- diff(grconvertY(c(0, lh), 'inches', 'npc'))
switch(side,
`1` = grconvertY(-line * y_off, 'npc', 'user'),
`2` = grconvertX(-line * x_off, 'npc', 'user'),
`3` = grconvertY(1 + line * y_off, 'npc', 'user'),
`4` = grconvertX(1 + line * x_off, 'npc', 'user'),
stop("Side must be 1, 2, 3, or 4", call.=FALSE))
}
addfiglab <- function(lab, xl = par()$mar[2], yl = par()$mar[3]) {
text(x = line2user(xl, 2), y = line2user(yl, 3),
lab, xpd = NA, font = 2, cex = 1.5, adj = c(0, 1))
}
par(mfrow = c(1, 2))
plot(0)
addfiglab("A")
plot(1000)
addfiglab("B")
答案 1 :(得分:2)
您可以使用cowplot::plot_grid
功能:
https://cran.r-project.org/web/packages/cowplot/vignettes/introduction.html
require(cowplot)
require(ggplot2)
set.seed(1234)
# Create plot "template" with some dummy data
gg <- ggplot(data = data.frame(1,2), aes(x = X, y = Y)) +
theme_light() +
theme(plot.margin = unit(c(10.5, 10.5, 5.5, 5.5), "points"))
# Create the actual plots
gg1 <- gg + geom_point(data = data.frame(X = 2, Y = 3))
gg2 <- gg + geom_point(data = data.frame(X = rnorm(100), Y = rnorm(100)))
plot_grid(gg1, gg2, labels = c("A", "B"))
答案 2 :(得分:1)
您只需要使用par("usr")
获取y轴限制,然后相应地设置文本:
set.seed(1234)
# Define the y value where the text is to be placed on the first graph
textY = 2
# Plot the graph, text and get the axis limits
plot(2,3)
text(x = 1.5,y = textY, "A", font = 2 )
yA = par("usr")
#Plot the second graph and get the axis limits
plot(rnorm(100))
yB = par("usr")
# Calculate the y value where to place the text on the second graph
new_yB = (textY-yA[3])/(yA[4]-yA[3])*(yB[4]-yB[3])+yB[3]
text(x = 1.5,y = new_yB, "B", font = 2)
par("usr")
将返回一个包含4个数字的向量:xLow,xHigh,yLow,yHigh
答案 3 :(得分:0)
另一种选择是使用mtext
和左对齐xpd=NA
:
set.seed(1234)
layout(mat=matrix(c(1,2,3,3,4,4,4,4), ncol=4))
plot(rnorm(100))
mtext(text=LETTERS[1], xpd=NA, side=3, adj=0, font=2)
plot(rnorm(100))
mtext(text=LETTERS[2], xpd=NA, side=3, adj=0, font=2)
plot(rnorm(100))
mtext(text=LETTERS[3], xpd=NA, side=3, adj=0, font=2)
plot(rnorm(100))
mtext(text=LETTERS[4], xpd=NA, side=3, adj=0, font=2)