-1

Good morning

I have a problem with the next graphic, I cannot delete "NA" bar, in my graphic I need only 1960 $ 1970s. How I can remove this bar in te next code?

3a 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") +
  theme_minimal()

Itried to remove "NA" in data frame with the next code

gap<- na.omit(gap)

but, when I print the cade "NA" bar is on the grapic again

stefan
  • 90,330
  • 6
  • 25
  • 51
rdediego
  • 1
  • 1
  • 1
    Welcome to SO. Your code is currently not [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) since we cannot access your dataset `gap`, but you can provide your data using `dput(gap)` or `dput(head(gap))` if you dataset is large. – jrcalabrese Nov 20 '22 at 15:03
  • 2
    You might be generating NAs when you use `filter` and/or `mutate` -- try using `na.omit` or [`remove_missing`](https://ggplot2.tidyverse.org/reference/remove_missing.html) after `filter` and `mutate`. – jrcalabrese Nov 20 '22 at 15:04

1 Answers1

0

You're likely creating NA values when using case_when - if the year isn't in those decades then R codes it NA. You could filter out, for example using similar code for the gapminder dataset:

library(gapminder)
library(tidyverse)

gapminder %>%
  filter(continent %in% c("Asia", "Africa")) %>% 
  mutate(decade = case_when(between(year,1960,1969)  ~ "1960s",
                            between(year,1970,1979)  ~ "1970s")) %>% 
  filter(!is.na(decade)) %>%
  ggplot(aes(x = factor(decade), y = gdpPercap, fill = continent)) +
  geom_col(position = "fill") +
  scale_fill_brewer(palette = 3, type = "qual") +
  theme_minimal()

If this doesn't solve the problem for your code then do give a sample of your data so we can figure out if there's another problem.

Andy Baxter
  • 5,833
  • 1
  • 8
  • 22