gpt4 book ai didi

r - 设置 y 轴位置时向内对齐 y 轴标签 "right"

转载 作者:行者123 更新时间:2023-12-04 08:41:39 27 4
gpt4 key购买 nike

在 R {ggplot2} 中,我想将最外层的轴标签向内对齐,当没有指定位置参数时,这对 x 和 y 轴标签没有问题(请参见下面的第一个图)。
但是,当 y 轴定位时 right hjust参数在 axis.text.y = element_text()似乎没有响应(见第二个图)。我知道 element_text 中不正式支持矢量化输入,但即使是长度为 1 的向量也不影响 y 轴标签的位置。
需要明确的是:我想要的输出类似于第一个图,但 x 轴位于顶部,y 轴位于右侧。目前,y 轴上的“许多”一词并未向内对齐。
这是一个错误吗?我需要指定一些其他参数吗?
任何帮助表示赞赏。

library(ggplot2)
library(dplyr)

p <- mtcars %>%
ggplot(aes(x = cyl, y = gear)) +
geom_point()

# labels are aligned nicely:
p +
scale_x_continuous(expand = c(0,0),
limits = c(4,8),
breaks = seq(4, 8, 1),
labels = c("few", "", "", "", "many")) +
scale_y_continuous(expand = c(0,0),
limits = c(3, 5),
breaks = seq(3, 5, 1),
labels = c("few", "", "many")) +
theme(
axis.text.x = element_text(
hjust = c(0, 0, 0, 0, 1)),
axis.text.y = element_text(
angle = 90,
hjust = c(0,0,1)
)
)
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.

# x labels are aligned nicely
# y labels do not respond to `hjust`
# 'many' should be aligned pointing inwards
p +
scale_x_continuous(expand = c(0,0),
position = "top",
trans = "reverse",
limits = c(8,4),
breaks = seq(8, 4, -1),
labels = c("few", "", "", "", "many")) +
scale_y_continuous(expand = c(0,0),
position = "right",
trans = "reverse",
limits = c(5, 3),
breaks = seq(5, 3, -1),
labels = c("few", "", "many")) +
theme(
axis.text.x = element_text(
hjust = c(0, 0, 0, 0, 1)),
axis.text.y = element_text(
angle = 90,
hjust = c(0,0,1)
)
)
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.

#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.

创建于 2020-10-26 由 reprex package (v0.3.0)

最佳答案

不确定这是否是一个错误,但我最近遇到了类似的问题。在我的情况下以及显然在你的情况下的解决方案是更具体并利用 axis.text.y.right :

library(ggplot2)
library(dplyr)

p <- mtcars %>%
ggplot(aes(x = cyl, y = gear)) +
geom_point()

p +
scale_x_continuous(expand = c(0,0),
position = "top",
trans = "reverse",
limits = c(8,4),
breaks = seq(8, 4, -1),
labels = c("few", "", "", "", "many")) +
scale_y_continuous(expand = c(0,0),
position = "right",
trans = "reverse",
limits = c(5, 3),
breaks = seq(5, 3, -1),
labels = c("few", "", "many")) +
theme(
axis.text.x = element_text(
hjust = c(0, 0, 0, 0, 1)),
axis.text.y.right = element_text(
angle = 90,
hjust = c(0,0,1)
)
)

关于r - 设置 y 轴位置时向内对齐 y 轴标签 "right",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64539478/

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