gpt4 book ai didi

r - 关于如何使用 R 和 ggplot2 绘制背靠背图的问题

转载 作者:行者123 更新时间:2023-12-04 18:18:47 27 4
gpt4 key购买 nike

我的目标是绘制一个金字塔图,就像所附的那样。

enter image description here

我发现了几个使用 ggplot 的例子,但我仍然在努力将我的例子用于我的数据(或我想要绘制的数据)。

structure(list(serial = c(40051004, 16160610, 16090310), DMSex = structure(c(2, 
2, 2), label = "Gender from household grid", labels = c(`No answer/refused` = -9,
`Don't know` = -8, `Interview not achieved` = -7, `Schedule not applicable` = -2,
`Item not applicable` = -1, Male = 1, Female = 2), class = "haven_labelled"),
dtotac = structure(c(-9, -9, -8), label = "DV: Total actual hours in all jobs and businesses", labels = c(`No answer/refused` = -9,
`Don't know` = -8, `Interview not achieved` = -7, `Item not applicable` = -1
), class = "haven_labelled")), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))

如何转换我的数据并绘制背靠背图?或者如何在不进行子集化的情况下定义 Gender 和 dtotac 变量?

我正在使用的代码
library(ggplot2)
library(plyr)
library(gridExtra)

SerialGenderWorkN <- data.frame(Type = sample(c('Male', 'Female', 'Female'),
11421, replace=TRUE),
dtotac = sample (0:60, 11421, replace=TRUE))

WrkFactor <- ordered(cut(SerialGenderWork$dtotac,
breaks = c(0, seq(20, 60, 10)),
include.lowest = TRUE))

SerialGenderWorkN$dtotac <- WrkFactor

ggplotWrk <- ggplot(data =SerialGenderWorkN, aes(x=dtotac))

ggplotWrk.female <- ggplotWrk +
geom_bar(data=subset(SerialGenderWorkN, Type == 'Female'),
aes( y = ..count../sum(..count..), fill = dtotac)) +
scale_y_continuous('', labels = scales::percent) +
theme(legend.position = 'none',
axis.title.y = element_blank(),
plot.title = element_text(size = 11.5),
plot.margin=unit(c(0.1,0.2,0.1,-.1),"cm"),
axis.ticks.y = element_blank(),
axis.text.y = theme_bw()$axis.text.y) +
ggtitle("Female") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_flip()

ggplotWrk.male <- ggplotWrk +
geom_bar(data=subset(SerialGenderWorkN,Type == 'Male'),
aes( y = ..count../sum(..count..), fill = dtotac)) +
scale_y_continuous('', labels = scales::percent,
trans = 'reverse') +
theme(legend.position = 'none',
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
plot.title = element_text(size = 11.5),
plot.margin=unit(c(0.1,0.2,0.1,-.1),"cm")) +
ggtitle("Male") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_flip() +
xlab("Work Hours")

## Plutting it together
grid.arrange(ggplotWrk.male, ggplotWrk.female,
widths=c(0.4, 0.4), ncol=2)

这是输出

enter image description here

如何在“男”和“女”图之间移动“工作时间”以显示?

最佳答案

您可以使用 top争论并使用 vjust 将其降低.

grid.arrange(ggplotWrk.male, ggplotWrk.female,
widths=c(0.4, 0.4), ncol=2,
top = textGrob("Work Hours",gp=gpar(fontsize=11,font=1), vjust=2))

关于r - 关于如何使用 R 和 ggplot2 绘制背靠背图的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56357636/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com