scale_x_discrete不标记N / A值

时间:2022-11-23 14:56:07

I am using ggplot2 to plot a histogram which contains some N/A values. When I label the x axis then my N/A bar will remain unlabelled (1), but when I instead not label my histogram, an automatic label for my N/A values appear (2).

我正在使用ggplot2绘制包含一些N / A值的直方图。当我标记x轴时,我的N / A栏将保持未标记(1),但是当我没有标记我的直方图时,会出现我的N / A值的自动标签(2)。

How can I achieve to get my N/A values to be labelled as such?

如何才能将我的N / A值标记为这样?

(1) labelled histogram - lack of a label for N/A values!

(1)标记直方图 - 缺少N / A值的标签!

doforaliving <- factor(rawdata$Q009)
ggplot(rawdata, aes(x=doforaliving)) + geom_histogram(binwidth=.5) + xlab("") + ylab("Number of Participants") + ggtitle("Are you working or studying?") + scale_x_discrete(breaks=c("1", "2", "3", "4", "na.value"), labels=c("Working", "Searching for work", "Continuing my studies", "Other", "NA"))

scale_x_discrete不标记N / A值

(2) unlabelled histogram - N/A values are labelled!

(2)未标记的直方图 - 标记N / A值!

doforaliving <- factor(rawdata$Q009)
ggplot(rawdata, aes(x=doforaliving)) + geom_histogram(binwidth=.5) + xlab("") + ylab("Number of Participants") + ggtitle("Are you working or studying?")

scale_x_discrete不标记N / A值

1 个解决方案

#1


1  

From the information you provided, I'd say: replace na.value by NA:

根据您提供的信息,我会说:用NA替换na.value:

set.seed(1)
library(ggplot2)
rawdata <- data.frame(doforaliving=as.factor(c(sample(1:4, 100, replace=T), rep(NA, 10))))
ggplot(rawdata, aes(x=doforaliving)) + 
  geom_histogram(binwidth=.5) + xlab("") + 
  ylab("Number of Participants") + 
  ggtitle("Are you working or studying?") + 
  scale_x_discrete(breaks=c("1", "2", "3", "4",NA), 
                   labels=c("Working", "Searching for work", "Continuing my studies", "Other", "NA"))

scale_x_discrete不标记N / A值

#1


1  

From the information you provided, I'd say: replace na.value by NA:

根据您提供的信息,我会说:用NA替换na.value:

set.seed(1)
library(ggplot2)
rawdata <- data.frame(doforaliving=as.factor(c(sample(1:4, 100, replace=T), rep(NA, 10))))
ggplot(rawdata, aes(x=doforaliving)) + 
  geom_histogram(binwidth=.5) + xlab("") + 
  ylab("Number of Participants") + 
  ggtitle("Are you working or studying?") + 
  scale_x_discrete(breaks=c("1", "2", "3", "4",NA), 
                   labels=c("Working", "Searching for work", "Continuing my studies", "Other", "NA"))

scale_x_discrete不标记N / A值