r - 使用不同数据集时文本相对于绘图区域的一致定位
问题描述
我生成了几个图,其中数据可能具有不同x
的y
范围。我希望在所有绘图中放置一个文本注释,相对于绘图区域的位置完全相同。
第一个图的示例,我在其中添加文本并以数据为单位annotate
定位它:x
y
library(tidyverse)
ggplot(mpg) +
geom_point(aes(displ, hwy)) +
annotate("text", x = 6, y = 20, label = "example watermark", size = 8) +
ggsave(filename = "mpg.jpg", width = 10, height = 9, dpi = 60)
x
然后根据与第一个图不同且y
范围不同的另一个数据集创建第二个图。
无需反复试验,将文本放置在相对于绘图区域完全相同的位置的最佳方法是什么?
ggplot(iris) +
geom_point(aes(Petal.Width, Petal.Length)) +
# I don't want to hardcode x and y in annotate
# annotate("text", x = 6, y = 20, label = "example watermark", size = 8) +
ggsave(filename = "iris.jpg", width = 10, height = 9, dpi = 60)
解决方案
您可以使用annotation_custom
. 这允许您grob
在绘图窗口的指定坐标处绘制图形对象 ( )。只需以“npc”为单位指定位置,从左下角的 (0, 0) 缩放到窗口右上角的 (1, 1):
library(ggplot2)
mpg_plot <- ggplot(mpg) + geom_point(aes(displ, hwy))
iris_plot <- ggplot(iris) + geom_point(aes(Petal.Width, Petal.Length))
annotation <- annotation_custom(grid::textGrob(label = "example watermark",
x = unit(0.75, "npc"), y = unit(0.25, "npc"),
gp = grid::gpar(cex = 2)))
mpg_plot + annotation
iris_plot + annotation
由reprex 包于 2020-07-10 创建(v0.3.0)
推荐阅读
- javascript - 二维数组根据条件替换值
- ios13 - iOS 13 Xcode UI 测试自动化类型不匹配
- security - 如何将静态文件的访问权限限制为特定的登录用户?
- ios - 如何在 Swift UI 中实现本地化
- flutter - 如何检测带有颤动/火焰的游戏中的滑动
- c++ - 通过终端在文件中输入时检测 EOF(文件结尾)的问题
- vue.js - vue-router 和 from 有什么区别:to
- java - 删除数据库中间的一些行后,有什么方法可以滚动 SQL 中的所有行?
- swift - SwiftUI 中的动态 NavigationLink 目的地?
- python - 如何更改我的数据以使其与损失一起工作:均方误差?