我試圖找出沿 x 軸(看起來像這里的 y 軸,因為我正在翻轉坐標)在變數型別之間添加一點空間的最佳方法。
如您所見,我按“型別”變數分面,但我有三個不同類別的“組”變數:種族、性別和地區。到目前為止,我已經得到了不同顏色的它們,這很有幫助,但理想情況下我可以在它們之間添加一點空白。有什么好主意嗎?
代碼:
order <- c("white", "black", "hispanic", "female", "male", "north", "south")
ggplot(d, aes(x = group, y = percent, fill = group))
geom_bar(stat = "identity")
facet_wrap(~type)
coord_flip()
scale_x_discrete(limits = order)
scale_fill_manual(values = c("white" = "skyblue",
"black" = "skyblue",
"hispanic" = "skyblue",
"male" = "indianred1",
"female" = "indianred1",
"north" = "goldenrod2",
"south" = "goldenrod2"))
theme_minimal()
theme(legend.position = "none")
資料示例:
structure(list(group = c("white", "white", "white", "black",
"black", "black", "hispanic", "hispanic", "hispanic", "male",
"male", "male", "female", "female", "female", "south", "south",
"south", "north", "north", "north"), percent = c(0.34, 0.23,
0.2, 0.04, 0.5, 0.3, 0.14, 0.52, 0.2, 0.13, 0.43, 0.34, 0.43,
0.3, 0.3, 0.14, 0.09, 0.42, 0.22, 0.1, 0.05), type = c("typeA",
"typeB", "typeC", "typeA", "typeB", "typeC", "typeA", "typeB",
"typeC", "typeA", "typeB", "typeC", "typeA", "typeB", "typeC",
"typeA", "typeB", "typeC", "typeA", "typeB", "typeC")), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -21L), spec = structure(list(
cols = list(group = structure(list(), class = c("collector_character",
"collector")), percent = structure(list(), class = c("collector_double",
"collector")), type = structure(list(), class = c("collector_character",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))

uj5u.com熱心網友回復:
實作所需結果的一種選擇是 4 切換到facet_grid. 為此,添加一個包含類別的列,您要根據這些類別對您的專案或groups 進行分組,然后可以將其用于y方向方面。這樣做的額外好處是您現在可以按類別而不是按顏色group。
library(ggplot2)
library(dplyr)
d <- d |>
mutate(
cat = case_when(
group %in% c("male", "female") ~ "sex",
group %in% c("south", "north") ~ "region",
TRUE ~ "race"
),
group = factor(group, levels = order),
cat = factor(cat, levels = c("region", "sex", "race"))
)
ggplot(d, aes(x = percent, y = group, fill = cat))
geom_col(orientation = "y", width = .75)
facet_grid(cat ~ type, scales = "free_y", space = "free_y")
scale_fill_manual(values = c(
"race" = "skyblue",
"sex" = "indianred1",
"region" = "goldenrod2"
))
theme_minimal()
theme(legend.position = "none", strip.text.y = element_blank())

uj5u.com熱心網友回復:
這絕對是一件復雜的事情,stefan 有一個很好的答案。請參閱此處了解一些其他想法:Control space between ticks discrete x axis
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/534937.html
標籤:r图表2面包裹
