我想突出显示 ggplot 带注释表的每一列的最大值。最好的结果是如果结果是一个 ggplot,我可以在代码的其余部分中使用它。
使用 ggpmisc 包的 annotate(…) 方法,我可以使用添加的表格创建一个绘图
library(ggplot2)
library(ggpmisc)
gg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species) ) +
geom_point() +
annotate(geom = "table",
x = Inf, y = 0,
label = list(head(iris,5 )),
size=2)
gg1
我找到了这个答案,我对其进行了修改以突出显示列而不是行的最大值: https://stackoverflow.com/a/72430256
library(ggplot2)
library(flextable)
library(magrittr)
iris %>%
flextable::flextable() -> iris_max_highlight
for(i in seq_len(ncol(iris)))
{
iris_max_highlight %<>% flextable::bold(which.max(iris[,i]), i)
}
iris_max_highlight
然后,我尝试以某种方式将结果与此答案结合起来,将修改后的表添加到图中,但无法使其工作:https://stackoverflow.com/a/60350244
最近的一个选项是使用
flextable::gen_grob
将 flextable
转换为 grob 并使用 patchwork::inset_element
: 将其添加到绘图中
library(ggplot2)
library(patchwork)
library(flextable)
library(magrittr)
gg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) +
geom_point()
ft <- flextable(head(iris))
for (i in seq_len(ncol(iris))) {
ft %<>% flextable::bold(which.max(head(iris)[, i]), i)
}
ft <- ft |>
fontsize(part = "all", size = 12)
gg1 +
inset_element(
gen_grob(ft, fit = "auto"),
left = 0.4, bottom = 0.01,
right = .99, top = .4
)