r - 当答案为 FALSE 或 TRUE 时如何创建 ggplot?

标签 r ggplot2 r-haven

当我的答案是 TRUE 或 FALSE 时,如何使用 ggplot 创建绘图?

这是我的代码:

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

> head(t.obese)
  Income obese
1  21600    TRUE
2   4000    TRUE
3  12720    TRUE
4  26772    TRUE

当我尝试创建绘图时,r 告诉我“不知道如何自动选择 Haven_labelled/vctrs_vctr/double 类型的对象的比例。默认为连续。 Fehler:stat_count() 只能有 x 或 y 美学。”

谢谢!

> dput(t.obese[1:10, ])
structure(list(Income = structure(c(1944, 4000, 16000, 19200, 
22800, 21600, 18000, 18000, 2000, 18000), label = "Wages,Salary from                    main job", format.stata = "%42.0g", labels = c(`[-5] in Fragebogenversion    nicht enthalten` = -5, 
 `[-2] trifft nicht zu` = -2), class = c("haven_labelled",      "vctrs_vctr", 
 "double")), obese = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 
TRUE, TRUE, TRUE)), row.names = c(NA, 10L), class = "data.frame")

最佳答案

如果您想比较不同肥胖人群的收入分布,那么您需要 obese = TRUE 和 obese = FALSE,这样您就可以进行比较

我随机创建了一个 non_obese 数据集只是为了进行比较。 另外,我删除了 Incomehaven_labelled 类,因为它在 reprex 渲染中导致了一些问题 [使用 haven::zap_labels ()

无论如何,希望以下内容能够帮助您入门

library(dplyr)
library(ggplot2)
library(haven)

obese <- 
structure(list(Income = structure(c(1944, 4000, 16000, 19200, 
                                    22800, 21600, 18000, 18000, 2000, 18000), 
                                  label = "Wages,Salary from main job", 
                                  format.stata = "%42.0g", 
                                  labels = c(`[-5] in Fragebogenversion nicht enthalten` = -5,
                                             `[-2] trifft nicht zu` = -2), 
                                  class = c("haven_labelled", "vctrs_vctr","double")), 
               obese = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,TRUE, TRUE, TRUE)), 
          row.names = c(NA, 10L), class = "data.frame"
          )


# remove the haven/labelled class of the income variable
obese <- 
  obese %>% 
  haven::zap_labels() 

non_obese <- 
  obese %>% 
  mutate(
    Income = Income - rnorm(1, mean = 1000, sd = 50),
    obese  = !obese
  )



full_data <- 
  bind_rows(obese, non_obese)


# Box plot 
full_data %>% 
  ggplot(
    aes(obese, Income)
  )+
  geom_boxplot(width = 0.5)+
  geom_point(position = position_jitter(width  = 0.05))

# Density plot
full_data %>% 
  ggplot(
    aes(Income,fill = obese)
  )+
  geom_density(alpha = 0.5)

reprex package于2020年12月3日创建(v0.3.0)

关于r - 当答案为 FALSE 或 TRUE 时如何创建 ggplot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65112037/

相关文章:

r - 如何修改 Shiny 应用程序中的绘图大小?

r - facet_wrap的百分比直方图

r - ggplot2 中的 scale_fill - 为 ggplots 列表中的每个图制作渐变颜色

Reading Haven在Stata中创建了dta文件 - 如何处理变量名中的点?

r - 在 R 中将自由之家索引转换为整洁的格式

R:将二进制分类变量转换为长数据格式

r - ggplot文本中的饼图标记恐怖

r - 在 ggplot2 中的 aes() 和 geom() 内部设置颜色和大小

r - 黑客在 Haven::read_sav() 的文件路径中包含特殊字符

r - 将 Haven_labelled 向量的标签提取为字符串向量