gpt4 book ai didi

r - 对齐ggplot2中的文本注释

转载 作者:行者123 更新时间:2023-12-04 10:09:12 26 4
gpt4 key购买 nike

这是一个测试df:

a <- 5:8
b <- c("A", "B", "C", "D")
df <- data.frame(a,b)

我想创建一个条形图并在每个条形上方添加文本,顶部下方一定距离,因此我使用 y=Inf, vjust=2 ,但是字母现在是按顶部对齐而不是底部对齐(即它们不在同一水平线上)。有没有办法改变它(对于“较短”的值,不必将值摆弄成 vjust=2.45 左右)?
ggplot(df, aes(x=b, y=a)) + geom_bar(stat="identity") +
scale_y_continuous(limits = c(0,9)) +
annotate('text', x=1, y=Inf, vjust=2, label = "a", parse=TRUE) +
annotate('text', x=2, y=Inf, vjust=2, label = "a", parse=TRUE) +
annotate('text', x=3, y=Inf, vjust=2, label = "b", parse=TRUE) +
annotate('text', x=4, y=Inf, vjust=2, label = "b", parse=TRUE)

enter image description here

最佳答案

答案很简单:使用单个“注释”命令而不是多个命令。
编辑:如果 parse参数设置为 TRUE (如您的代码段),此方法失败。
:) 祝你好运。

library(ggplot2)

a <- 5:8
b <- c("A", "B", "C", "D")
df <- data.frame(a,b)

ggplot(df, aes(x=b, y=a)) + geom_bar(stat="identity") +
scale_y_continuous(limits = c(0,10)) +
# This is the difference to yor code:
annotate("text", x = 1:4, y = Inf, vjust=2, label = c("a", "a", "b", "b"))

enter image description here

这实际上包含在 annotate 的 R 文档中:(最后一行 ?annotate)
p + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))

关于r - 对齐ggplot2中的文本注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25973559/

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