symbolrush
symbolrush

Reputation: 7457

ggplot throws error `label not found`, while `label` is clearly there

I can plot the labels of the following df using geom_text:

df <- data.frame(
  x = c(610, 426, 569, 253), 
  y = c(-226, -276, -364, -185), 
  label = c("accomplishments per week", "hours worked per week", "perceived adequacy of accomplishments", "energy level"),
  stringsAsFactors = FALSE
)

ggplot(df, aes(x, y)) + geom_text(aes(label = label))

enter image description here

However, when trying to use the same plotting mechanism with my real data I get an error:

Error in FUN(X[[i]], ...) : object 'label' not found

Why is that and how can I solve it?


Here's my real data df1:

df1 <- structure(list(type = c("var", "var", "var", "var"),
                  id = c(1,2, 4, 7), 
                  x = c(610, 426, 569, 253), y = c(-226, -276, -364, -185), 
                  label = c("accomplishments per week", "hours worked per week",  "perceived adequacy of accomplishments", "energy level"), 
                  from = c(NA_real_,NA_real_, NA_real_, NA_real_), 
                  to = c(NA_integer_, NA_integer_,NA_integer_, NA_integer_), 
                  polarity = c(NA_character_, NA_character_, NA_character_, NA_character_), 
                  group = c(1L, 1L, 1L, 1L)), .Names = c("type","id", "x", "y", "label", "from", "to", "polarity", "group"),
             row.names = 7:10, class = c("cld", "data.frame")
             )

df

   type id   x    y                                 label from to polarity group
7   var  1 610 -226              accomplishments per week   NA NA     <NA>     1
8   var  2 426 -276                 hours worked per week   NA NA     <NA>     1
9   var  4 569 -364 perceived adequacy of accomplishments   NA NA     <NA>     1
10  var  7 253 -185                          energy level   NA NA     <NA>     1

Upvotes: 4

Views: 1848

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70603

Your df1 is of class cld and data.frame (see second line in the above output of str). It would seem that ggplot doesn't like that the object is cld first. To go around that, using as.data.frame forces df1 to become data.frame class only. You can use class(df1) to check it out, or see str(df1) output below. Notice the "Classes" line.

> str(df1)
Classes ‘cld’ and 'data.frame': 4 obs. of  9 variables:
 $ type    : chr  "var" "var" "var" "var"
 $ id      : num  1 2 4 7
 $ x       : num  610 426 569 253
 $ y       : num  -226 -276 -364 -185
 $ label   : chr  "accomplishments per week" "hours worked per week" "perceived adequacy of accomplishments" "energy level"
 $ from    : num  NA NA NA NA
 $ to      : int  NA NA NA NA
 $ polarity: chr  NA NA NA NA
 $ group   : int  1 1 1 1

If you coerce it to data.frame, it works fine.

ggplot(as.data.frame(df1), aes(x = x, y = y, label = label)) +
  geom_text()

enter image description here

Upvotes: 5

Related Questions