问题
Say I have a plot like this:
library(ggplot2)
dat <- data.frame(x = 1:10, y = 1:10)
ggplot(dat, aes(x = x, y = y)) +
geom_point() +
xlab("Test label")
Does ggplot2
allow for fixing the xlab
positioning at a specific point? Say I wanted the label to appear centered at the point where x = 7
(rather than the default centering).
回答1:
This isn't exactly what you want, but you can adjust the horizontal justification in the theme
options. This is relative between 0 and 1, not tied to the data coordinates. 0
is left-justified (left side of the axis), 1
is right-justified, and the default 0.5
as centered. In this case, we can set hjust = 0.7
. (Though an axis from 1 to 10 has length 10 - 1 = 9, so we could get nitpicky and use (7 - 1) / (10 - 1) = 2/3
... I'll leave it to you how precise you want to be.)
ggplot(dat, aes(x = x, y = y)) +
geom_point() +
xlab("Test label") +
theme(axis.title.x = element_text(hjust = 0.7))
回答2:
Here is another way, but the one from @Gregor Thomas is nicer
library(ggplot2)
dat <- data.frame(x = 1:10, y = 1:10, label = 'Test label')
p <- ggplot(dat, aes(x = x, y = y)) +
geom_point() +
xlab('') # no x-label
#xlab("Test label")
p + geom_text(aes(label = label, x = 7, y = -Inf), vjust = 3) +
coord_cartesian(clip = 'off') # This keeps the labels from disappearing
来源:https://stackoverflow.com/questions/65616313/ggplot2-r-fix-x-axis-label-at-a-specific-point-relative-to-plot