Home > OS >  Error when creating waffle chart - object cannot be coerced
Error when creating waffle chart - object cannot be coerced

Time:03-03

Attempting to make a simple waffle chart with the below vector pie:

  rideable_type number_of_trips
  <ord>                   <dbl>
1 Classic                    58
2 Electric                   36
3 Docked                      6

The function I am using is:

waffle(pie, rows=6)

This function returns the following error:

Error in FUN(X[[i]], ...) : 
  'list' object cannot be coerced to type 'double'

I'm sure that error is because rideable_type is characters, because when I run:

waffle(pie$number_of_trips, rows=6)

It runs just fine, but the legend names are A, B, C. I just want the the legend to correspond to the rideable_type. I'm sure I could do that manually...but it seems unnecessary. Thank you.

CodePudding user response:

I figured out I can use setNames to solve the problem:

pie <- setNames(pie$number_of_trips, c('Classic','Electric','Docked'))
waffle(pie, rows=5, legend_pos='bottom')

Produces what I need:

enter image description here

I realized that waffle thought my vector was unnamed. I believed the function would automatically use the first column. Still not sure waffle doesn't, but this solved my question.

CodePudding user response:

The first argument needs to be a named vector, so you can do:

waffle(setNames(df$number_of_trips, df$rideable_type), rows = 6)

enter image description here

  • Related