我有一些資料被分為 25 個類別和 6 個父組,每個父組中的類別數量奇數(3 到 5 個)。對于每個父組,我使用 facet_wrap 根據類別創建單獨的面板,然后使用 grid.arrange 將父組圖一起顯示。問題是,由于每個父組中的類別數量不同,繪圖寬度會自動調整大小。有沒有辦法手動設定繪圖寬度或創建空面板以使寬度一致?
簡單的娛樂在這里:
library(dplyr)
library(gridExtra)
x <- c(1, 2, 3, 4, 1, 2)
y <- c(3, 3, 3, 3, 3, 3)
category <- c("category a", "category b", "category c", "category d", "category e", "category f")
group <- c("group one", "group one", "group one", "group one", "group two", "group two")
df <- data.frame(x, y, category, group)
group_one <- df %>% filter(group=="group one")
g1 <- ggplot(group_one, aes(x=x, y=y))
geom_point()
facet_wrap(~category, nrow=1)
labs(title="Group One")
group_two <- df %>% filter(group=="group two")
g2 <- ggplot(group_two, aes(x=x, y=y))
geom_point()
facet_wrap(~category, nrow=1)
labs(title="Group Two")
grid.arrange(g1, g2)
這是上面的代碼產生的 - 注意不均勻的面板寬度。如何使第二組面板與第一組面板的寬度相同,右側有空白空間?
如果有一種更簡單的替代方法可以根據組創建帶有副標題的這種型別的情節安排,我很樂意聽到它!謝謝!
uj5u.com熱心網友回復:
一種選擇是使用該patchwork包。在您的示例代碼的情況下,您可以執行
library(patchwork)
g1 / (g2 plot_spacer())
作為一種更普遍的方法,你可以
- 把你的情節放在一個串列中
- 制作一個包含每組類別數的向量
- 回圈遍歷繪圖串列,向每個繪圖添加一個分隔符,并使用
plot_layout使面板對齊的方式設定每個子圖和分隔符的寬度。
注意:為了使示例更有趣,我添加了第三組。
編輯要按組為點著色,您可以使用命名的顏色向量,它將顏色分配給組。通過這種方式,您可以將顏色分配給 的顏色引數geom_point。在下面的代碼中,我使用默認的 ggplot2 顏色,但您可以根據需要設定顏色。
library(dplyr)
library(ggplot2)
library(forcats)
library(stringr)
x <- c(1, 2, 3, 4, 1, 2, 1:3)
y <- c(3, 3, 3, 3, 3, 3, 1:3)
category <- c("category a", "category b", "category c", "category d", "category e", "category f", "category d", "category e", "category f")
group <- c("group one", "group one", "group one", "group one", "group two", "group two", "group three", "group three", "group three")
df <- data.frame(x, y, category, group)
# Named vector of colors
colors <- scales::hue_pal()(length(unique(df$group)))
names(colors) <- unique(df$group)
p <- df %>%
# Set order of group
mutate(group = forcats::fct_inorder(group)) %>%
split(.$group) %>%
purrr::imap(function(.data, .title) {
ggplot(.data, aes(x=x, y=y))
geom_point(color = colors[.title])
facet_wrap(~category, nrow=1)
labs(title = stringr::str_to_title(.title))
})
# Make a vector containing number of categories per group
ncat <- df %>%
group_by(group) %>%
summarise(n = n_distinct(category)) %>%
tibble::deframe()
ncat_max <- max(ncat)
library(patchwork)
p <- purrr::imap(p, function(x, y) {
ncat <- ncat[[y]]
n_spacer <- ncat_max - ncat
# Add spacer to each plot and set widths
x plot_spacer() plot_layout(ncol = 2, widths = c(ncat, n_spacer))
})
wrap_plots(p, nrow = length(p))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315849.html
