【问题标题】:Creating line graph for variable against proportion of another variable using ggplot in R使用R中的ggplot为变量创建与另一个变量的比例的折线图
【发布时间】:2020-08-20 06:53:01
【问题描述】:

我有一个针对女性和劳动力的大型调查数据集。答案是具有不同数据标签的分类值。该数据集包含 63,000 个响应和 2000 个不同的变量,但我在下面附上了相关变量的一个小 sn-p 以及数据标签。

我需要为按地理位置划分的劳动力中女性的年龄分布构建一个折线图。我有年龄、目前工作的数据(值为 0 和 1;0 为否,1 为是)和居住地(值为 1 和 2;1 为城市,2 为农村),但我想不出办法因为我是初学者,所以合并数据并绘制它。 我希望在 y 轴上取当前就业的女性比例,在 x 轴上取年龄,得到两条线,一条代表城市,一条代表农村。

我附上了一张我想到的输出图像和变量的 sn-p。由于我无法添加两个单独的图像,因此我将它们放在一起。 我知道我可以使用 facet_grid 显示城乡,但我无法弄清楚如何组合这些数据。

Image link

如果有任何帮助,我将不胜感激。

【问题讨论】:

  • 欢迎来到 SO!为了帮助我们帮助您,您能否通过共享您的数据样本和您尝试过的代码来重现您的问题?只需在控制台中输入dput(head(NAME_OF_DATASET, 20))(这将给出您数据的前20行)并将以structure(....开头的输出复制并粘贴到您的帖子中。另见how to make a minimal reproducible example

标签: r ggplot2


【解决方案1】:

欢迎!就像@stefan 说的,如果我们看到你的一些数据会更容易。所以我根据你的描述生成了一些。

library(tidyverse)
library(magrittr)

place = sample(c(1,2),63000, replace = TRUE) # 1 = Urban and 2 = Rural
employ = sample(c(0,1),63000, replace = TRUE) # 0 = Not Employed and 1 = Employed
age = sample(c(20:45), 63000, replace = TRUE) # Age


df = data.frame(place,employ, age)     
df %>% 
  group_by(age,place,employ) %>%  
 summarise(n = n()) %>% 
 mutate(prop = n/(n[1]+n[2])) %>% 
 filter(employ == 1) %>%
 mutate(newplace = case_when(place == 1 ~ "Urban", place == 2 ~ "Rural")) %>%  
 ggplot(., aes(x = age, y = prop,  color=newplace))+
 geom_line(aes(linetype = newplace))+
 scale_color_manual(values = c("blue", "red")) + #Or color of your choice
 labs(title = "Proportion of Women Employed:\n Comparing Urban and Rural Communities", y = "Proportion of Employed Women", color = "", 
 linetype = "")+ # Removed legend titles since they were redundany
 theme_classic()+
 theme(plot.title = element_text(hjust =.5), legend.position = "bottom")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多