在R中重新缩放金字塔图

vs91vp4v  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(93)

我怎样才能在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"))

代码生成图:

njthzxwz

njthzxwz1#

这里有一种方法,使用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, 20, 40, NA)
pq$layout$panel_params[[2]]$x$minor_breaks <- c(NA, 10, 20, 30, 40)

qt <- ggplot_gtable(pq)
cowplot::plot_grid(qt)

相关问题