r - 如何将带有变量的格式化文本添加到分面包装的 ggplot?
问题描述
我试图弄清楚如何为每个子图添加一个不错的 R^2 = 值。
现在我可以在绘图上添加我想要的值(来自单独的数据框),但我不知道如何在它前面添加一个斜体和上标的“R^2 =”。
任何建议表示赞赏。感谢您的时间!
example_df <- data.frame(x = c(1,2,5,7,8,9,10),
y = c(1,3,5,7,8, 9, 10),
grp = c("a", "a", "b","b","b", "c", "c"))
grp_info <- data.frame( grp = c("a", "b", "c"),
num = c(0.5, 0.75, 1))
plt <- ggplot(example_df, aes(x = x, y=y, group = grp)) +
geom_point() +
facet_wrap(vars(grp), ncol = 2, scales = "free")+
annotate(geom = "text", x = -Inf, y = Inf, label = grp_info$num, hjust = 0, vjust =1)
print(plt)
如果我只想将“R^2 =”格式化得很好,那么以下方法可以工作,但它不允许我从单独的数据框中添加值。
plt <- ggplot(example_df, aes(x = x, y=y, group = grp)) +
geom_point() +
facet_wrap(vars(grp), ncol = 2, scales = "free")+
annotate(geom = "text", x = -Inf, y = Inf, label = paste("paste(italic(R) ^ 2,\"=\")"), parse = TRUE, hjust = 0, vjust =1)
我在评论中迟迟提出的最后一点是,理想情况下,这种添加将是多行的,允许添加另一个变量表达式。
解决方案
我认为最好将您的注释分配为geom_text
调用 - 这与某些方面的作用相同,但会与您的调用annotate
保持同步:facet_wrap
library(ggplot2)
example_df <- data.frame(
x = c(1, 2, 5, 7, 8, 9, 10),
y = c(1, 3, 5, 7, 8, 9, 10),
grp = c("a", "a", "b", "b", "b", "c", "c")
)
grp_info <- data.frame(grp = c("a", "b", "c"),
num = c(0.5, 0.75, 1))
ggplot(example_df, aes(x = x, y = y, group = grp)) +
geom_point() +
facet_wrap(vars(grp), ncol = 2, scales = "free") +
geom_text(
data = grp_info,
aes(
x = -Inf,
y = Inf,
label = paste0("italic(R)^2", "==", num)
),
parse = TRUE,
hjust = 0,
vjust = 1
)
由reprex 包于 2021-03-24 创建(v1.0.0)
推荐阅读
- coordinates - 有没有办法将地球位置地心转换为某个特定位置的切线坐标?
- java - 如何测试有其他测试的登录页面?
- java - 如何创建可在打盹模式和省电模式下工作的 PhoneStateListener?
- python - 如何将选定的行移动到熊猫中的下一个相邻列?
- c# - 调用 PostAsync 方法会使应用程序崩溃
- python - 左加入具有相同键的多条记录的熊猫
- c - 如何修复 copy_from_user 不起作用?
- ios - IBDesignable 的自定义背景颜色属性不会根据目标更新
- python - 如何从 saved_model (SSD MobileNet) 创建一个 tflite 文件
- python - 从元组列表中生成所有可能的路径