【问题标题】:How to combine tables to create one bar plot in ggplot?如何组合表格以在 ggplot 中创建一个条形图?
【发布时间】:2020-12-02 11:41:03
【问题描述】:

我想知道,如何组合我的表格来创建一个条形图。 我首先变异并创建了新列......但答案是对或错

master1 <- master %>%
  mutate(underweight = BMI < 18.5,
         normal = between(BMI, 18.5, 24.9),
         overweight = between(BMI, 25, 29.9),
         obese = between(BMI, 30, 34.9),
         extreme = BMI > 35)

由于我不知道如何从该表创建条形图,因此我将它们拆分为新表:

t.underweight<-master1 %>%
  filter(Income>0,underweight==TRUE) %>%
  select(Income,underweight)

t.normal<-master1%>%
  filter(Income>0,normal==TRUE)%>%
  select(Income,normal)

t.overweight<-master1%>%
  filter(Income>0,overweight==TRUE)%>%
  select(Income,overweight)

t.obese<-master1%>%
  filter(Income>0,obese==TRUE)%>%
  select(Income,obese)

t.extreme<-master1%>%
  filter(Income>0,extreme==TRUE)%>%
  select(Income,extreme)

也许在变异后有一种更简单的指导方法,如果是的话,我会很感激学习如何。如果不是,我怎样才能结合这张表来创建一个条形图? 我的第二个变量将是“收入”...在 y 轴上

【问题讨论】:

    标签: r ggplot2 filter bar-chart dplyr


    【解决方案1】:

    你在找这个吗?

    library(tidyverse)
    set.seed(1)
    bmi <- runif(100, 10, 50)
    income <- rnorm(100, 400, 10)
    id <- 1:100
    
    df <- data.frame(id = id, bmi = bmi, income = icnome)
    
    res <- df %>% 
      mutate(BMI_cat = cut(
        x = bmi,
        breaks = c(0, 18.5, 25, 30, 35, Inf),
        labels = c("underweight", "normal", "overweight", "obese", "extreme"),
        ordered_result = T
      ))
    
    ggplot(res, aes(income)) +
      geom_histogram(bins = 10) +
      facet_wrap(~BMI_cat, scales = "fixed")
    

    【讨论】:

    • 您好 Yuriy,感谢您的帮助.. 我正在寻找类似的东西...
    • 太棒了!如果您认为此答案对您有帮助,您可以通过单击此答案左侧的勾号来接受它:)
    • 是的,当然.. 还有一个问题,但是当答案是 TRUE 和 FALSE 时怎么可能呢? t.extreme&lt;-master1%&gt;% filter(Income&gt;0,extreme==TRUE)%&gt;% select(Income,extreme) &gt; head(t.extreme) Income extreme 1 21600 TRUE 2 4000 TRUE 3 12720 TRUE 4 26772 TRUE
    猜你喜欢
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多