如何用 plus/minus 符号交换 x 轴刻度标签 table

How to swap x-axis tick labels with plus/minus signs table

我正在努力弄清楚如何将 ggplot2 中的 x 轴标签从常规标识更改为不太规则的 plus/minus 符号,以关联每个条上特定处理的添加或不存在。如下图所示:

说实话,我都不知道这种坐标轴标注是怎么叫的。它在生物科学表示中更为常见,我习惯于使用 Gimp 或其他图像编辑软件更改绘图以手动添加它。这有点像在图表下方添加一个 table 来标识每个条件。

有几种方法可以做到这一点;这是一个可能的解决方案:

library(tidyverse)
library(cowplot)

df <- tibble(
  Names = c(rep("A", 11), rep("B", 7),
             rep("C", 4), rep("D", 12)),
  Values = rnorm(34, 25, 10),
  `Cpd 1` = c(rep("+", 11), rep("+", 7),
              rep("-", 4), rep("-", 12)),
  `Cpd 2` = c(rep("+", 11), rep("-", 7),
              rep("+", 4), rep("-", 12)),
)

p1 <- df %>% 
  ggplot(aes(x = Names, y = Values)) +
  geom_col(width = 0.25) +
  theme_minimal(base_size = 14) +
  theme(axis.text.x = element_blank(),
        axis.title.x = element_blank()) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.05)))

p2 <- df %>% 
  pivot_longer(-c(Names, Values)) %>% 
  ggplot(aes(x = Names, fct_rev(name), label = value)) +
  geom_text(size = 10) +
  labs(x = NULL, y = NULL) +
  theme_minimal(base_size = 14) +
  theme(panel.grid = element_blank(), axis.text.x = element_blank())

plot_grid(p1, p2, ncol = 1, align = "hv", rel_heights = c(0.75, 0.25))

reprex package (v2.0.1)

于 2022-05-13 创建

如果您还需要组标签:

library(tidyverse)
library(cowplot)

df <- tibble(
  Names = c(rep("A", 11), rep("B", 7),
             rep("C", 4), rep("D", 12)),
  Values = rnorm(34, 25, 10),
  `Cpd 1` = c(rep("+", 11), rep("+", 7),
              rep("-", 4), rep("-", 12)),
  `Cpd 2` = c(rep("+", 11), rep("-", 7),
              rep("+", 4), rep("-", 12)),
)

p1 <- df %>% 
  ggplot(aes(x = Names, y = Values)) +
  geom_col(width = 0.4) +
  theme_minimal(base_size = 14) +
  theme(axis.text.x = element_text(size = 18),
        axis.title.x = element_blank(),
        axis.line = element_line(size = 2.5)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.05)))

p2 <- df %>% 
  pivot_longer(-c(Names, Values)) %>% 
  ggplot(aes(x = Names, fct_rev(name), label = value)) +
  geom_text(size = 10) +
  labs(x = NULL, y = NULL) +
  theme_minimal(base_size = 14) +
  theme(panel.grid = element_blank(), axis.text.x = element_blank())

plot_grid(p1, p2, ncol = 1, align = "hv", rel_heights = c(0.7, 0.3))

reprex package (v2.0.1)

于 2022-05-13 创建

不调用第二个绘图的潜在解决方案是将其绘制在 pseudo-discrete 轴上并相应地放置中断。

library(ggplot2)

df <- data.frame(
    cpd1 = c("-", "-", "+", "+"),
    cpd2 = c("-", "+", "-", "+"),
    value = rpois(4, 10)
)

# Pre-form interaction
df <- transform(df, int = interaction(cpd1, cpd2, sep = "\n"))

ggplot(df, aes(as.numeric(int), value)) +
    geom_col() +
    scale_x_continuous(
        breaks = c(0.5, seq_len(nrow(df))),
        labels = c("Cpd 1\nCpd 2", as.character(df$int))
    )

reprex package (v0.3.0)

于 2022-05-13 创建

您甚至可以通过添加隐藏第一个刻度线:

  theme(
    axis.ticks.x.bottom = element_line(colour = c(NA, rep("black", nrow(df))))
  )