0

I am attempting to make a histogram of weights faceted by gender. Unfortunately, gender is not known for some participants, but I do have weights for them. This has resulted in levels that are used, but are not relevant to me and unfortunately I can't seem to figure out how to make it so the NA histogram is not shown.

Here is my code:

KYHH %>%
 ggplot(aes(x = Weight)) +
 geom_histogram() +
 facet_grid(~ Gender, drop = TRUE) +
 ggtitle("Weight by Gender")

Can you help?

Thanks in advance!

Kelly
  • 135
  • 1
  • 1
  • 10
  • 2
    Welcome to StackOverflow! Please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of your data so I / the rest of the folks can fiddle with it – Punintended Jun 18 '18 at 21:18

2 Answers2

2

Kelly, if you do not provide a reproducible example it is hard to help you. Yet, by your description, you could try to filter the observations with NAs in th Gender variable.

 library(dplyr)
 KYHH %>% filter(!is.na(Gender)) %>%
         ggplot(aes(x = Weight)) +
         geom_histogram() +
         facet_grid(~ Gender, drop = TRUE) +
         ggtitle("Weight by Gender")
Brian
  • 7,900
  • 1
  • 27
  • 41
Nicolás Velasquez
  • 5,623
  • 11
  • 22
0

Another alternative solution can be to use, drop=TRUE.

# create a factor variable with several levels
occupation<- factor(c("astronaut","baker","cobbler","driver",
                      "engineer","fisherman","gambler"))
occupation
[1] astronaut baker     cobbler   driver    engineer  fisherman gambler  
Levels: astronaut baker cobbler driver engineer fisherman gambler

# drop the last 3 levels
df<-occupation[1:4, drop=TRUE]
df
[1] astronaut baker     cobbler   driver   
Levels: astronaut baker cobbler driver
# drop levels 1,4,7
df1<- occupation[c(2:3,5:6), drop=TRUE]
df1
[1] baker     cobbler   engineer  fisherman
Levels: baker cobbler engineer fisherman
mnm
  • 1,962
  • 4
  • 19
  • 46