我需要排列 2 个具有相同 Y 轴但类似于金字塔图的图表,但区别在于 X 轴显示不同的变量。我有一个数据集,其中包含两个不同的变量,我想将其用于 X 轴。这是一个例子:
如何在 R 中执行此操作(理想情况下使用 ggplot,但我对其他解决方案持开放态度)?
我使用cow.plot、grid、ggarrange的努力仅并排绘制图,作为单独的图。
更新:添加小样本数据集(基因=Y轴)
"gene","mutations","proportion"
"VHL",165,0.491
"PBRM1",145,0.355
"NF2",21,0.209
"PTEN",122,0.199
"EGFR",98,0.181
"NF1",16,0.172
"PIK3CA",91,0.15
"BAP1",18,0.139
"TP53",58,0.127
"CDH1",117,0.085
"MET",22,0.075
"SMAD4",33,0.075
"RB1",30,0.055
"APC",45,0.05
"PPP6C",23,0.047
"NSD1",19,0.04
"TSC1",28,0.039
"ALB",48,0.037
"ATM",18,0.035
"STK11",12,0.033
您可以通过首先将
proportion
和 mutations
变量旋转到一列中,将两个变量绘制在单个图(或多个小图)中。以下是创建此可视化的两种可能方法。
library(tidyverse)
df |>
pivot_longer(-gene) |>
mutate(value = if_else(name %in% 'proportion', -value*1000, value)) |>
ggplot(aes(x = value, y = gene, fill = name)) +
geom_col() +
scale_x_continuous(breaks = scales::breaks_extended(n = 8)) +
theme_minimal() +
labs(fill = '', x = '', y = '') +
theme(legend.position = 'top',
panel.grid.major = element_blank())
df |>
pivot_longer(-gene) |>
mutate(value = if_else(name %in% 'proportion', -value, value),
name = factor(name, levels = c('proportion', 'mutations'))) |>
ggplot(aes(x = value, y = gene, fill = name)) +
geom_col() +
facet_wrap(~name, scales = 'free_x') +
labs(fill = '', x = '', y = '') +
theme_minimal() +
theme(legend.position = 'top',
panel.grid.major = element_blank(),
panel.spacing = unit(0, 'lines'))
创建于 2024-04-06,使用 reprex v2.0.2