我正在努力弄清楚如何將 ggplot2 中的 x 軸標簽從常規標識更改為不那么常規的加號/減號,以關聯每個條上特定處理的添加或缺失。如下圖所示:

老實說,我什至不知道這種型別的軸標注是怎么稱呼的。它在生物科學表示中更為常見,我習慣于使用 Gimp 或其他影像編輯軟體手動添加它來更改繪圖。這類似于在圖表下方添加一個表格來識別每個條件。
uj5u.com熱心網友回復:
不呼叫第二個繪圖的潛在解決方案是將其繪制在偽離散軸上并相應地放置中斷。
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 包(v0.3.0)于 2022-05-13 創建
您甚至可以通過添加以下內容來隱藏第一個刻度線:
theme(
axis.ticks.x.bottom = element_line(colour = c(NA, rep("black", nrow(df))))
)
uj5u.com熱心網友回復:
有幾種方法可以做到這一點;這是一種潛在的解決方案:
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 包(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 包(v2.0.1)創建于 2022-05-13
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474400.html
上一篇:r將數學符號添加到x軸文本
