我怎样才能在 R 中生成一个金字塔图,其尺度的起点不是 0?
我正在尝试使用以下代码在 R 中生成金字塔图,如下所示。我想重新缩放它,使其不是从 0 开始,而是从两半开始 0.7。有人可以帮忙吗?下面是我的代码,附件是结果图
library(tidyverse)
library(ggpol)
df <- tibble(
Population = c(5, 8.7, 16.7, 24.8, 38, -4.6, -6.4, -16.1, -39.6, -55.3),
Gender = c("Male", "Male", "Male", "Male", "Male", "Female", "Female",
"Female", "Female", "Female"),
AgeBand = c("65-69", "70-74", "75-79", "80-84", "85+", "65-69", "70-74",
"75-79", "80-84", "85+")
)
ggplot(df, aes(x = AgeBand, y = Population, fill = Gender)) +
geom_bar(stat = "identity") +
facet_share(~Gender, dir = "h", scales = "free", reverse_num = TRUE) +
# note: scales = "free"
coord_flip() +
theme_minimal() +
labs(y = "Count", x = "Age Band", title = " ") +
scale_fill_manual(values = c("pink", "blue"))
代码的结果图:
这是一种使用 ggplot_build() 的方法,可以让您了解构成渲染图的底层部分。然后我们可以手动更新这些,使用 ggplot_gtable() 重组数据,以便我们可以使用 cowplot::plot_grid() 来显示。请注意,我删除了主题,因为它会导致出现错误消息。
q <- ggplot(df1, aes(x = AgeBand, y = Population, fill = Gender)) +
geom_bar(stat = "identity") +
facet_share(~Gender, dir = "h", scales = "free", reverse_num = TRUE) + # note: scales = "free"
coord_flip() +
labs(y = "Count", x = "Age Band", title = " ") +
scale_fill_manual(values = c("pink", "blue"))
pq <- ggplot_build(q)
#Update the breaks according to how you want them to display. The first
#set of breaks is what appears first, on the left, and the second is the
#one on right
pq$layout$panel_params[[1]]$x$breaks <- c(NA, -40.0, -20.0, -0.7)
pq$layout$panel_params[[1]]$x$minor_breaks <- c(-50, -40, -30, -20, -10, NA)
pq$layout$panel_params[[2]]$x$breaks <- c(0.7, 15, 30, NA)
pq$layout$panel_params[[2]]$x$minor_breaks <- c(NA, 10, 20, 30, 40)
qt <- ggplot_gtable(pq)
cowplot::plot_grid(qt)