ggplot 访问数据标签而不是数据值

ggplot accessing data labels rather than data values

我已将一些 SPSS 数据导入到 R 中,数据已标记,我想绘制标签名称,而不是值。我试过下面的方法,但它打印出值

library(labelled)
library(tidyverse)

cols <- c("White", "Red", "Black", "Green", "Brown", "Pink", "Orange")
letters <- c("D", "E", "F", "G", "H", "I", "J")

# add labels to the color values
tmp <- diamonds %>% 
 mutate(color = as.character(color)) %>%
 set_value_labels(color = setNames(letters, cols)) 

ggplot(tmp) + geom_bar(aes(x=print_labels(color)))

图表仍然使用颜色值作为 y 轴,而不是标签。我们如何绘制数据框标签?

基于 colsletters,我会为它们创建一个数据框,然后(通过 dplyr::inner_join)与 tmp 合并以创建一个新列,其中包含您想要的沿 x 轴的名称。

library(ggplot2)
library(dplyr)
library(tibble)

#Create a dataframe key to get the color names for each category and make a new column with the names.
col_key <- attributes(tmp$color)$labels %>%
  as.data.frame() %>%
  dplyr::rename(cols = 1) %>%
  tibble::rownames_to_column("color")

tmp <- dplyr::inner_join(tmp,
                         col_key, by = "color")

ggplot(tmp) +
  geom_bar(aes(x = cols))
library(haven)

cols <- c("White", "Red", "Black", "Green", "Brown", "Pink", "Orange")
letters <- c("D", "E", "F", "G", "H", "I", "J")

tmp <- diamonds %>% 
  mutate(color = as.character(color)) %>%
  set_value_labels(color = setNames(letters, cols)) 

ggplot(tmp) + geom_bar(aes(x=as_factor(color)))

利用 haven 库,我们可以使用 as_factor(x) 命令,将标签转换为因子