r - ggplot:将轴文本放在绘图内
问题描述
我想在绘图区域内放置标签。
这是一个示例图:
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()
我知道我可以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())
对此问题的评论 [移动轴标签 ggplot ] 表明这margin
是在当前 ggplot 中执行此操作的非 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
解决方案
有趣的问题。我不知道这样做的优雅方式,但margin()
如果你真的想要它,确实将文本移动到绘图区域。为了使其工作,您还需要使用正确的参数而不是仅使用左侧参数。
我也尝试过使用 top 和 bottom 参数,但似乎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
推荐阅读
- javascript - Javascript / React Native - 如何在两个不同的对象数组之间进行交叉检查?
- mysql - phpmyadmin 这是索引大小吗?
- python - 我们如何将列表作为函数中的参数?
- ruby - 初始化方法中的'self.class.class_method_name'有什么作用?
- java - 创建没有重复的随机整数数组
- angular - Nativescript queryParamsMap 在返回时不起作用
- visual-studio-2019 - 如何在 Visual Studio 2019 中启用 Microsoft 文档弹出窗口,如 NetBeans 中的 java 文档
- typescript - 来自另一个 ts 文件的打字稿导入功能 - 文件不是模块错误
- html - 边框半径和表格边框 - 边框突出在右侧
- python - 在 Google Colab 中打开 JPG 文件