2

I have a generic plot_data(data) method. Sometimes the incoming data has all NAs for the variable I use for fill and this causes the error

Error in seq.default(h[1], h[2], length.out = n) : 
  'to' must be a finite number

For example:

df <- data.frame(
  x = c(1, 2, 3, 4), 
  y = c(10, 15, 20, 25),
  foo = factor(c(NA, NA, NA, "yes"), levels=c("yes", "no"))
)

ggplot(df, aes(x=x, y=y, fill=foo))+geom_bar(stat = "identity")  # works
ggplot(df[1:3, ], aes(x=x, y=y, fill=foo))+geom_bar(stat = "identity")  # error

I don't see why the plot shouldn't render in case 2 (just with all grey bars). Is there an easy way to overcome this?

3 Answers 3

3

You can use fct_explicit_na from the forcats package to make missing values an explicit factor level. (Note that addNA from the base package won't work here; the latter adds NA as a level, but won't cause it to show up in plots.)

ggplot(df[1:3, ], 
       aes(x=x, y=y, fill=forcats::fct_explicit_na(foo)))+
  geom_bar(stat = "identity")

Aside: If you do have other values & just want a different default colour for NA ones, you can change the option in scale_fill_discrete(na.value = "some colour other than grey")

1

Kind of yucky...

ggplot(df[1:3,], aes(x=x, y=y, if(!all(is.na(foo))){fill=foo})) +
  geom_bar(stat = "identity")
0

grey means no fill. For example, the following one will give a grey drawing:

ggplot(df, aes(x=x, y=y))+geom_bar(stat = "identity") In your example, when the row with foo = "yes" was included, the rows with foo = NA were actually not filled with colors, and only the last row was filled. However, when the last row was excluded, all the values in column foo become NA. As the error suggests, the end of to in the fill mapping has to be a finite number, not NA. A way to circumvent this is to convert NA into strings, such as:

ggplot(df[1:3, ], aes(x=x, y=y, fill=ifelse(is.na(foo), "NA", foo)))+geom_bar(stat = "identity")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.