R 中的因子函数返回 NA

Factor function in R returning NAs

我有一个包含 'months' 列和协调值的数据框。当我创建图表时,月份是按字母顺序排列的。我想使用因子函数对月份进行排序,但现在我的图表只显示了五月和 'NAs'。

xnames<-c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
Data$Month<-factor(Data$Month, levels = xnames)
ggplot(DAtaTidy_MergeRWPeaks2, (aes(x=factor(Month, xnames), y=Volume)), na.rm=TRUE) + 
    geom_bar() 

我尝试将因子嵌入到 ggplot 函数中,但结果相同。当我从 'xnames' 中删除 'May' 时,图表只显示 NA。

我们看不到您的数据,但该行为表明 Data$Month 包含一个未包含在您的级别术语 xnames 中的值。有没有拼写错误?我建议您比较 levels(as.factor(Data$Month))xnames - 它肯定会告诉您问题所在。

显示您遇到的相同问题的示例数据集:

yums <- c('soup', 'salad', 'bread')
nums <- c(10, 14, 5)
df1 <- data.frame(yums, nums)

yum.levels <- c('soup', 'salad', 'bread', 'pasta')
ggplot(df1, aes(x=factor(yums, yum.levels), y=nums)) + geom_col()

这给了你这个:

...但是如果我们拼错其中一个(比如在 yums 中大写 "Soup"),您会得到:

yums1 <- c('Soup', 'salad', 'bread')
nums <- c(10, 14, 5)
df2 <- data.frame(yums1, nums)

yum.levels <- c('soup', 'salad', 'bread', 'pasta')
ggplot(df2, aes(x=factor(yums1, yum.levels), y=nums)) + geom_col()