在R {ggplot2}中,我想将最外侧的轴标签向内对齐,当未指定position参数时,这对于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.
由reprex package(v0.3.0)于2020-10-26创建
答案 0 :(得分:2)
不确定这是否是错误,但是最近我遇到了类似的问题。就我而言,显然也针对您而言,解决方案是更具体,并使用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)
)
)