gpt4 book ai didi

r - 使用 ggplot 绘图时 hjust 和 vjust 做什么?

转载 作者:行者123 更新时间:2023-12-02 01:49:03 29 4
gpt4 key购买 nike

每次我使用 ggplot 绘制绘图时,我都会花一点时间尝试像这样的行中的 hjust 和 vjust 的不同值

+ opts(axis.text.x = theme_text(hjust = 0.5))

使轴标签在轴标签几乎接触轴的位置对齐,并与轴齐平(可以这么说,与轴对齐)。但是,我真的不明白发生了什么事。通常,hjust = 0.5 会给出与 hjust = 0.6 截然不同的结果,例如,我无法仅通过使用不同的值来弄清楚它。

任何人都可以向我指出 hjust 和 vjust 选项如何工作的全面解释吗?

最佳答案

hjustvjust 的值仅定义在 0 到 1 之间:

  • 0表示左对齐
  • 1 表示右对齐

来源:ggplot2,Hadley Wickham,第 196 页

(是的,我知道在大多数情况下您可以在超出此范围的情况下使用它,但不要期望它以任何特定方式运行。这超出了规范。)

hjust 控制水平对齐,vjust 控制垂直对齐。

一个例子应该可以清楚地说明这一点:

td <- expand.grid(
hjust=c(0, 0.5, 1),
vjust=c(0, 0.5, 1),
angle=c(0, 45, 90),
text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) +
geom_point() +
geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) +
facet_grid(~angle) +
scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here

<小时/>

要了解更改轴文本中的 hjust 时会发生什么,您需要了解轴文本的水平对齐方式不是相对于 x 轴定义的,而是相对于整个绘图定义的(其中包括 y 轴文本)。 (在我看来,这是不幸的。相对于轴进行对齐会更有用。)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() +
ylab("Very long label for y") +
theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

<小时/>

探索轴标签的 vjust 对齐会发生什么:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) +
xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) +
xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) +
xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

关于r - 使用 ggplot 绘图时 hjust 和 vjust 做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7263849/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com