如何向ggplot2 R中的轴添加潜台词

How to add subtext to axes in ggplot2 R

对于主要的 y-axis 和 x-axis,我有像 "Tank's Ratio" 和 "Counts" 这样的通用标题。我想要第二行标签,我在其中指定比率和计数。例如。在 "Tank's Ratio" 下方,我希望“# in water/# in sand”的字体较小,但要沿着 y-axis。 x-axis 同样如此。 这是基本代码

data <- data.frame(set = c(1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4), density = c(1, 3, 3, 1, 3, 1, 1, 1, 3, 3, 1, 3), counts = c(100, 2, 3, 76, 33, 12, 44, 13, 54, 36, 65, 1), ratio = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 90, 1))

library(ggplot2)

ggplot(data, aes(x = counts, y = ratio)) + 
  geom_point() + 
  ylab("Tank's Ratio") + 
  xlab("Counts") 

这不是最优雅的解决方案,但希望对您有所帮助:

library(ggplot2)
library(gridExtra)
library(grid)

首先,创建没有 ylab 的绘图:

g <- ggplot(data, aes(x = counts, y = ratio)) + 
  geom_point()  +
  ylab("") + 
  xlab("Counts") 

然后为两个轴添加副标题:

g2 <- grid.arrange(g, 
                   bottom = textGrob("in water/ # in sand", 
                                     x = 0.55, y = 1, gp = gpar(fontsize = 9)),
                   left = textGrob("in water/ # in sand",  rot = 90, 
                                   x = 1.5, gp = gpar(fontsize = 9)))

最后,添加 y-axis

的描述
grid.arrange(g2, 
             left = textGrob("Tank's Ratio",  rot = 90, 
                             x = 1.7, gp = gpar(fontsize = 12)))

您可以添加 x 和主标题。

编辑: 这太可笑了!

  #library(extrafont)
#loadfonts(dev="win")
library(tidyverse)
data %>%
ggplot(aes(x=counts, y=ratio)) + geom_point() +
labs(y=expression(atop(bold("Tank's Ratio"),atop(italic("#in water #in sand")))))+
  theme_minimal()+
  theme(axis.title.y = element_text(size=15,family="Comic Sans MS"))

原文:

library(tidyverse) 

      data %>%
    ggplot(aes(x=counts, y=ratio)) + geom_point() +
    labs(y="Tank's Ratio \n #in Water#in sand")

您可以使用以下代码,定义边距、轴标题和 sub-titles 自己:

我们使用theme来增加底部和左边距,并抑制自动生成的轴标题。

我们使用 annotate 生成用作轴标题的文本和 sub-title,如有必要,文本会旋转。

我们生成绘图,将其转换为 grob,然后 grob 我们可以关闭裁剪并显示绘图。

g1 <- ggplot(data = data, aes(x = counts, y = ratio, group = 1)) +
  geom_point()  + 

  ## increase margin size for left and bottom and
  ## remove the axis titles
  theme(plot.margin = unit(c(1, 1, 4, 4), "lines"),
        axis.title.y = element_blank(),
        axis.title.x = element_blank() ) +

  ## define the plotting area to NOT include the annotations
  coord_cartesian(xlim = c(0, 100), ylim= c(0, 100), expand = FALSE) +

  ## annotate y axis
  annotate(geom = "text", x = -9, y = 50, label = "Tank's Ratio", angle = 90, size = 5) +
  annotate(geom = "text", x = -5, y = 50, label = "#in water/#in sand", angle = 90, size = 4) +

  ## annotate x axis
  annotate(geom = "text", x = 50, y = -5, label = "Counts", size = 5) +
  annotate(geom = "text", x = 50, y = -9, label = "#in water/#in sand", size = 4)

## turn off  clipping for axis extra labels
g2 <- ggplot_gtable(ggplot_build(g1))
g2$layout$clip[g2$layout$name == "panel"] <- "off"
grid::grid.draw(g2)

这会产生下图:

请告诉我这是否是您想要的。