【问题标题】:scale_x_discrete does not label N/A valuesscale_x_discrete 不标记 N/A 值
【发布时间】:2014-01-04 21:43:36
【问题描述】:

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

我怎样才能让我的 N/A 值被标记为这样?

(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"))

(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?")

【问题讨论】:

  • 1) 提供您的数据样本 2) 执行@lukeA 建议的操作,即强制使用标签 3) 对没有 NA 和 droplevels 的数据进行子集化 4) 更改您的 factor(..., levels = c()) 5) 提供您的数据样本 6) 发布您的数据的str()

标签: r histogram ggplot2


【解决方案1】:

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

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"))

【讨论】:

  • 是的,这对我有帮助。非常感谢!
  • @TilHund,因为您的 x 轴是您不需要 breaks 的因素,所以使用 labels 就足够了。 binwidth 也不是必需的。
  • @Henrik,谢谢。那就更好了!我仍然需要学习很多关于 R 和 ggplot2 的知识!
猜你喜欢
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多