如何在ggplot2 R

时间:2019-01-08 13:51:56

标签: r ggplot2 axes subtitle

对于主要的y轴和x轴,我有通用的标题,例如“坦克的比率”和“计数”。我想在标签的第二行指定比率和计数。例如。在“水箱比”的正下方,我希望“ y在水中/#在沙子中”使用较小的字体,但沿y轴。 x轴类似。 这是基本代码

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") 

3 个答案:

答案 0 :(得分:2)

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

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轴的描述

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

enter image description here

答案 1 :(得分:2)

您可以使用以下代码,自行定义边距,轴标题和副标题:

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

我们使用annotate生成用作轴标题和副标题的文本,如有必要,将旋转文本。

我们生成图,将其放在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)

这将产生以下图片:

enter image description here

请让我知道这是否是您想要的。

答案 2 :(得分:1)

您可以添加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"))

enter image description here

原始:

library(tidyverse) 

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