如何将属性用于条形图标签。 R

How to use attributes into barplot labeling. R

我得到了一个数据集,其中包含以下问题的答案:

“在过去的 2 周内,您是否对做事没有兴趣?”

并且有几个答案。我可以用这个命令看到它们:

> attributes(base$mhealth_1)$labels
             Don't know                 Refused          Not applicable 
                     -9                      -8                      -5 
                Missing              Not at all            Several days 
                     -3                       1                       2 
More than half the days        Nearly every day 
                      3                       4 

数据分布:

> table(base$mhealth_1)

   1    2    3    4 
6601 2137  905 1759 

所以我正在绘制条形图:

使用此代码:

ggplot(base) +
 aes(x = mhealth_1) +
 geom_histogram(bins = 30L, fill = "#B22222") +
 theme_minimal()

如何在 x 轴上使用 $labels

这里有一些附加信息:

> class(base$mhealth_1)
[1] "haven_labelled" "vctrs_vctr"     "double"    

这是数据示例:

> dput(example)
structure(list(mhealth_1 = structure(c(1, 1, 1, 3, 1, 1, 1, 3, 
2, 3), labels = c(`Don't know` = -9, Refused = -8, `Not applicable` = -5, 
Missing = -3, `Not at all` = 1, `Several days` = 2, `More than half the days` = 3, 
`Nearly every day` = 4), label = "g11 - Over the last 2 weeks, have you had little interest in doing things?", class = c("haven_labelled", 
"vctrs_vctr", "double")), mhealth_2 = structure(c(1, 3, 1, 2, 
2, 1, 1, 3, 4, 1), labels = c(`Don't know` = -9, Refused = -8, 
`Not applicable` = -5, Missing = -3, `Not at all` = 1, `Several days` = 2, 
`More than half the days` = 3, `Nearly every day` = 4), label = "g12 - Over the last 2 weeks, have you been feeling down, depressed or hopeless", class = c("haven_labelled", 
"vctrs_vctr", "double"))), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

我们可以用attributes提取。基于post,它是一个命名向量。使用该命名向量匹配并替换 'mhealth_1' 的值以创建新列并将其用于绘图

nm1 <-  attributes(base$mhealth_1)$labels
base$mhealth_1_lbl <- setNames(names(nm1), nm1)[as.character(base$mhealth_1)]

library(ggplot2)
 ggplot(base) +
  aes(x = mhealth_1_lbl, y = mhealth_1) +
  geom_col(fill =  "#B22222") +
  theme_minimal()

-输出

由于您的数据看起来像调查数据,我猜您可能需要条形图而不是直方图。此外,由于您的数据是 class labelled(可能通过 haven 从 SPSS 导入),您可以通过 haven::as_factor.

将其转换为标记因子

使用一些随机示例数据试试这个:

library(haven)
library(ggplot2)

set.seed(42)

base <- data.frame(
  mhealth_1 = haven::labelled(sample(1:4, 100, replace = TRUE),
                              labels = c("Don't know" = -9,
                                         "Refused" = -8,
                                         "Not applicable" = -5,
                                         "Missing" = -3,
                                         "Not at all " = 1,
                                         "Several days " = 2,
                                         "More than half the days" = 3,
                                         "Nearly every day" = 4))  
)

ggplot(base) +
  aes(x = haven::as_factor(mhealth_1)) +
  geom_bar(fill = "#B22222") +
  theme_minimal()