我按年龄分类按性别在R中创建了人口金字塔样式条形图。在上一步中,我按年龄和性别汇总了数据分组,以获得实习计数。然后我将男性计数乘以-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
结果图:
你的一个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()