And*_*rew 4 plot text r ggplot2
我有一些代码,我经常使用它们来生成大量的条形图。条形由沿 x 轴的标签聚集在一起,然后每个单独的条形在条形本身的顶部都有一个标签。有时,单个条形标签的文本会超出绘图区域的顶部并被截断——具体取决于 x 轴标签的长度、单个条形标签的长度以及条形本身的高度。
我可以手动调整scale_y_continuous(limits=c(0,100))
每个图以使其看起来不错。例如,如果条形的高度达到 100% 但标签很长,我可能会使用:scale_y_continuous(limits=c(0,140),breaks=c(0,25,50,75,100))
。这将 y 轴刻度线停止在 100% 处,但在绘图区域的顶部为我的标签留下了额外的空间。如果条形图仅达到 40% 且标签较短,则将 y 限制保留在 c(0,140) 看起来很糟糕,因为 100% 标记上方有太多空白。
因为我制作了大量这些图,所以我想要一种方法来自动确定如何scale_y_continuous
为每个图设置限制。手动操作太费时间了。
有没有办法测试标签是否被截断或超出绘图区域?如果是这样,我可以通过测试以查看标签是否被切断,然后稍微扩展 y 限制直到没有截断,从而迭代我的方式以获得漂亮的图。
我不认为这是可以做到的。我认为这归结为您没有完全理解所ggplot2
基于的语法。特别是如何ggplot
从数据值映射到美学值。
这可以通过一个简单的思想实验直观地理解:
library(ggplot2)
data(mtcars)
p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars)))
# consider
p + geom_text()
# vs
p + geom_text(size= 15)
Run Code Online (Sandbox Code Playgroud)
第一个情节p + geom_text()
和第二个情节有什么区别p + geom_text(size=15)
?从数据(结构)的角度来看,它们是相同的。唯一的区别是用于从数据元素映射到美学的缩放比例。但我的理解是,从数据元素到像素元素的映射是不存储的;因此您无法查看结果位置。
通过检查ggplot
对象的结构,这种预感似乎很明显:
p2 <- p + geom_text()
str(p2)
List of 9
$ data :'data.frame': 32 obs. of 11 variables:
..$ mpg : num [1:32] 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
..$ cyl : num [1:32] 6 6 4 6 8 6 8 4 4 6 ...
..$ disp: num [1:32] 160 160 108 258 360 ...
..$ hp : num [1:32] 110 110 93 110 175 105 245 62 95 123 ...
..$ drat: num [1:32] 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
..$ wt : num [1:32] 2.62 2.88 2.32 3.21 3.44 ...
..$ qsec: num [1:32] 16.5 17 18.6 19.4 17 ...
..$ vs : num [1:32] 0 0 1 1 0 1 0 1 1 1 ...
..$ am : num [1:32] 1 1 1 0 0 0 0 0 0 0 ...
..$ gear: num [1:32] 4 4 4 3 3 3 3 4 4 4 ...
..$ carb: num [1:32] 4 4 1 1 2 1 4 2 2 4 ...
$ layers :List of 2
..$ :Classes 'proto', 'environment' <environment: 0x0000000015eb15f8>
..$ :Classes 'proto', 'environment' <environment: 0x0000000015f6d0a0>
$ scales :Reference class 'Scales' [package "ggplot2"] with 1 field
..$ scales: list()
..and 23 methods, of which 9 are possibly relevant:
.. add, clone, find, get_scales, has_scale, initialize, input, n, non_position_scales
$ mapping :List of 3
..$ x : symbol wt
..$ y : symbol mpg
..$ label: language rownames(mtcars)
$ theme : list()
$ coordinates:List of 1
..$ limits:List of 2
.. ..$ x: NULL
.. ..$ y: NULL
..- attr(*, "class")= chr [1:2] "cartesian" "coord"
$ facet :List of 1
..$ shrink: logi TRUE
..- attr(*, "class")= chr [1:2] "null" "facet"
$ plot_env :<environment: R_GlobalEnv>
$ labels :List of 3
..$ x : chr "wt"
..$ y : chr "mpg"
..$ label: chr "rownames(mtcars)"
- attr(*, "class")= chr [1:2] "gg" "ggplot"
Run Code Online (Sandbox Code Playgroud)
如您所见,没有存储各种几何对象(在本例中为文本)的坐标像素位置。我猜这是因为ggplot2
它旨在以交互方式使用,但这只是一个猜测。也就是说,您可以轻松更改情节。保留绘图的唯一原因是通过ggsave
或grDevices
函数之一(png
等),在这种情况下,图形将保存到文件中。
如果您查看 Hadley 关于 ggplot 的书中的图 3.7,它是图形生成过程的示意图,似乎是这种情况,从数据元素到像素位置的映射的存储不是保存,而是每次生成。
...如果有人对ggplot
的内部工作有更深入的了解/已经检查了源代码有不同的了解,请插话,我会更新或删除我的答案。