问题描述
我已将一些 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 轴,而不是标签。我们如何绘制数据框标签?
解决方法
基于 cols
和 letters
,我将为这些创建一个数据框,然后(通过 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)命令,将标签转换为因子