ggplot:将轴标签放在图内

5
我希望能在绘图区域内放置标签。
这是一个示例图表:
library(ggplot2)

set.seed(123)
random_word <- function() paste(sample(letters, 10, replace = T), collapse='')
dat <- data.frame(x = replicate(4, random_word()),
                  y = runif(5*4, 0, 100))

ggplot(dat, aes(x = x, y = y)) +
  geom_point() +
  coord_flip() +
  theme_minimal()

enter image description here

我知道可以使用 geom_text 来实现我想要的结果:
ggplot(dat, aes(x = x, y = y)) +
  geom_point() +
  geom_text(data = dat[1:4,],
            aes(label=x), 
            y = 1, 
            hjust=0, vjust=-1 ) +
  coord_flip() +
  theme_minimal() +
  theme(axis.text.y = element_blank())

enter image description here

对于这个问题的评论 [ 移动ggplot轴标签] 表明,在当前的ggplot中,margin 是非hacky的方法,但它似乎不能将轴文本移动到绘图区域内。

# doesn't do the trick
ggplot(dat, aes(x = x, y = y)) +
  geom_point() +
  coord_flip() +
  theme_minimal() +
  theme(axis.title.y = element_text(margin = margin(l = 50)))

有没有一种优雅的方法通过设置theme()参数来获得这种输出结果?

我的sessionInfo()是:

> sessionInfo()
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.3

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] ggthemes_4.1.0  forcats_0.4.0   stringr_1.4.0   dplyr_0.8.0.1   purrr_0.3.1     readr_1.3.1    
 [7] tidyr_0.8.3     tibble_2.0.1    ggplot2_3.1.0   tidyverse_1.2.1

首先,您想移动 axis.text.y ,这样当您测试该注释并且它不起作用时,实际上您甚至没有更改正确的元素,但这不是主要问题。 margin() 明显会更改边距。标签仍然会在轴线和绘图边框之间的区域中打印,因此 margin 无法将标签带到图内。 除非有像顶部/底部/等位置绘图的选项(例如 scale_x_discrete(position = "inside"))那样的选项,我不知道有没有,所以我猜您最好的选择是使用您的 hacky 解决方案。 - M--
1个回答

1
有趣的问题。我不知道有什么优雅的方法可以做到这一点,但是如果您确实希望将文本移动到绘图区域中,margin() 可以实现。为了使其工作,您还需要调整右侧参数,而不仅仅是左侧参数。

我也尝试过调整上下参数,但似乎 margin() 在这里确实无效。 但是,您可以使用 vjust 将其垂直移开与网格线。

还请注意,我纠正了您将坐标轴标题移动而不是坐标轴文本的错误。

ggplot(dat, aes(x = x, y = y)) +
geom_point() +
coord_flip() +
theme_minimal() +
theme(axis.text.y = element_text(vjust = -0.7,
                                 margin = margin(l = 20, r = -50))) # note the negative value for r

点击此处查看输出


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接