[英]Adjust axis limits on facet_share population pyarmid
我使用 geom_bar 和 facet_share 創建了一個人口金字塔。 但是,數據標簽不適合具有當前軸限制或面板大小的面板。
我試過強制面板大小,但這只會按比例增加所有內容的大小。 我也試過設置 ylim,但這會增加兩個方向的軸。
我希望面板中有足夠的空間讓數據標簽可見。
#Here is the data
AgeGroupDat <-
structure(list(sex = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), levels = c("Male", "Female"), class = "factor"), Age_Group = c("00 - 20", "16 - 38", "18 - 34", "20 - 41", "32 - 54", "41 - 63", "48 - 69", "50 - 73", "62 - 86", "76 - 98", "00 - 20", "16 - 38", "18 - 34", "20 - 41", "32 - 54", "41 - 63", "48 - 69", "50 - 73", "62 - 86", "76 - 98" ), n = c(19318, 19050, 13948, 17416, 13893, 12495, 11038, 10813, 4751, 612, -19915, -15443, -11091, -13599, -11969, -11525, -10442, -10119, -4124, -367)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))
#And here is the plot
AgeGroupDat %>%
ggplot(aes(x = Age_Group, y = n, fill = sex))+
geom_bar(stat = "identity")+
geom_text(data = subset(AgeGroupDat,
sex == "Female"),
aes(label = abs(n)),
hjust = -0.3,
size = 3,
#position = position_stack(vjust = -.01)
)+
geom_text(data = subset(AgeGroupDat,
sex == "Male"),
aes(label = abs(n)),
hjust = 1.2,
size = 3,
#position = position_stack()
)+
coord_flip()+
facet_share(~sex, dir = "h", scales = "free", reverse_num = TRUE)+
theme_classic()+
scale_fill_manual(values = c("#9a0138","#000775"))+
labs(title = "test")+
labs(subtitle = "test")+
labs(caption = "test")+
labs(y = NULL)+
labs(x = NULL)+
labs(fill = "Member Sex")+
theme(legend.position = "none")+
ylim(-25000, 25000)
實現所需結果的一種選擇是切換到ggh4x
package,它通過facetted_pos_scales
允許為每個面板單獨設置比例。 但是,這樣做需要手動刪除其中一個y
刻度的軸文本。 此外,為了很好地居中標簽,我們必須通過panel.spacing.x = unit(0, "pt")
刪除面板間距,並為y
軸文本設置相同的邊距。
library(ggplot2)
library(ggh4x)
ggplot(AgeGroupDat, aes(y = Age_Group, x = n, fill = sex)) +
geom_bar(stat = "identity") +
geom_text(
aes(label = abs(n), hjust = ifelse(sex == "Female", -.3, 1.3)),
size = 3
) +
scale_fill_manual(values = c(Female = "#9a0138", Male = "#000775"), drop = FALSE) +
facet_wrap(~sex, scales = "free") +
facetted_pos_scales(
x = list(
scale_x_continuous(
labels = abs, expand = c(0, 2500, 0, 0),
limits = c(-20000, 0)
),
scale_x_continuous(
expand = c(0, 0, 0, 2500),
limits = c(0, 20000)
)
),
y = list(
scale_y_discrete(position = "right"),
scale_y_discrete(labels = NULL)
)
) +
labs(
x = NULL, y = NULL, fill = "Member Sex",
title = "test",
subtitle = "test",
caption = "test"
) +
theme_classic() +
theme(
axis.text.y.right = element_text(margin = margin(0, 2.2, 0, 2.2)),
legend.position = "bottom",
panel.spacing.x = unit(0, "pt")
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.