如何将图例放在R的字幕区域内

问题描述

我正在使用R studio / R Markdown创建图,有些使用ggplot,有些使用基本R功能。我想为每幅图插入一个标题,其中包含与此处所示示例相似的图例:

有人可以建议如何将我的绘图图例(由ggplot和base R函数构建)放置在标题中,如本示例所示?

我在网上搜索后发现可以使用类似的东西

p +  labs(caption="Figure S1: This is the Figure Legend") 

但是,我找不到如何将图例嵌入到标题中,也找不到针对使用基数R绘制的图的解决方案。

有些解决方案需要Latex,但是我不能在该项目中使用Latex。

解决方法

您只需将图例推到底部并添加自定义标题-包括一个计数器即可获取编号的图:

library(ggplot2)
# using the internal iris dataset
iris
# set counter to zero
NR <- 0

# Add counter and build plot
NR <- NR + 1
legend <- paste0("Fig. ",NR,": This is a Plot about...:")
ggplot2::ggplot(iris,aes(Sepal.Length,Petal.Width,color = Species)) +
  ggplot2::geom_point() +
  ggplot2::labs(color= legend) +
  ggplot2::theme(legend.position = "bottom")


# Add counter and build second plot
NR <- NR + 1
legend <- paste0("Fig. ",aes(Sepal.Width,Petal.Length,color = Species)) +
  ggplot2::geom_point() +
  ggplot2::labs(color= legend) +
  ggplot2::theme(legend.position = "bottom")

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...