我正在R中创建人口金字塔样式的条形图,其中按年龄类别和性别列出了工作实习的数量。在上一步中,我总结了按年龄和性别分组的数据,以得出实习人数。然后,我将Male计数乘以-1以进行正确的图形格式化。
在我手动更改geom_bars
的颜色之前,一切都很好。当我手动设置它们或使用scale_fill_manual
选项时,图表将旋转。也不太清楚如何更改字体。
此代码有效
#WEs
pyramidWE2 <- ggplot(WE2, aes(x = Age, y =n, fill = Gender)) +
geom_bar(data = subset(WE2, Gender == "F"), stat = "identity") +
geom_bar(data = subset(WE2, Gender == "M"), stat = "identity") +
scale_y_continuous(breaks=seq(-100,100,10),labels=abs(seq(-100,100,10))) +
#commented out: scale_fill_manual(values =c("pink","light blue")) +
#commented out: labs(x = "Age(Years)", y = "Number of WE's", title = "Number of Work Experiences by Gender, Colorado, 2018", font.lab="Trebuchet MS")
coord_flip()
pyramidWE2
结果图:
但是此代码可旋转图形并删除图例
#WEs
pyramidWE2 <- ggplot(WE2, aes(x = Age, y =n, fill = Gender)) +
geom_bar(data = subset(WE2, Gender == "F"), stat = "identity") +
geom_bar(data = subset(WE2, Gender == "M"), stat = "identity") +
scale_y_continuous(breaks=seq(-100,100,10),labels=abs(seq(-100,100,10))) +
scale_fill_manual(values =c("pink","light blue")) +
labs(x = "Age(Years)", y = "Number of WE's", title = "Number of Work Experiences by Gender, Colorado, 2018", font.lab="Trebuchet MS")
coord_flip()
pyramidWE2
结果图:
答案 0 :(得分:0)
您的ggplot函数之一缺少'+'
。 (在labs()
之后)。
library(tidyverse)
WE2 <- data.frame(
Age = rep(seq(20, 60, 5), 2),
Gender = rep(c('H', 'F'), each = 9),
n = rnorm(18, 40, 20) %>% ceiling()
) %>%
mutate(n = ifelse(Gender == 'F', -n, n))
WE2 %>% ggplot(aes(x = Age, y = n, fill = Gender)) +
geom_bar(data = subset(WE2, Gender == 'H'), stat = "identity") +
geom_bar(data = subset(WE2, Gender == 'F'), stat = "identity") +
scale_y_continuous(breaks = seq(-100,100,10), labels = abs(seq(-100,100,10))) +
scale_fill_manual(values = c("pink", "light blue")) +
labs(x = "Age(Years)", y = "Number of WE's", title = "Number of Work Experiences by Gender, Colorado, 2018", font.lab="Trebuchet MS") +
coord_flip()