You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot中移除NA条形?仅保留1960s和1970s分组

解决ggplot中NA条形的问题

你的问题出在新生成的decade列存在NA值,而你执行的na.omit(gap)只是处理了原始数据框中的NA,并没有过滤掉后续管道中新增的decade为NA的行,这些行最终被ggplot识别为一个类别,从而出现NA条形。

以下是两种可行的解决办法:

方法一:在数据处理阶段过滤NA(推荐)

在mutate之后、ggplot之前,添加filter(!is.na(decade))来移除decade为NA的行,从源头上剔除不需要的数据:

gap %>%
  filter(region %in% c("Southern Europe", "South America", "Australia and New Zealand", "Western Asia", "Western Africa")) %>% 
  mutate(decade = case_when(
    between(year,1960,1969)  ~ "1960s",
    between(year,1970,1979)  ~ "1970s"
  )) %>%
  filter(!is.na(decade)) %>%  # 新增该行过滤decade的NA
  ggplot(aes(x = factor(decade), y = gdp, fill = region)) +
  geom_col(position = "fill") +
  scale_fill_brewer(palette = 3, type = "qual") +
  theme_minimal()

方法二:在绘图时隐藏NA类别

如果你不想修改数据,可以通过scale_x_discrete的参数直接隐藏NA对应的条形:

gap %>%
  filter(region %in% c("Southern Europe", "South America", "Australia and New Zealand", "Western Asia", "Western Africa")) %>% 
  mutate(decade = case_when(
    between(year,1960,1969)  ~ "1960s",
    between(year,1970,1979)  ~ "1970s"
  )) %>%
  ggplot(aes(x = factor(decade), y = gdp, fill = region)) +
  geom_col(position = "fill") +
  scale_fill_brewer(palette = 3, type = "qual") +
  scale_x_discrete(na.translate = FALSE) +  # 新增该行隐藏NA类别
  theme_minimal()

补充说明

你之前用的na.omit(gap)只处理了原始gap数据框中的NA值,但mutate生成decade时,所有不在1960-1979区间的year都会让decade变成NA,这些行依然留在管道传递的数据中,所以ggplot会把NA当作一个单独的x轴类别显示出来。

内容的提问来源于stack exchange,提问作者rdediego

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:45:31