ggplot抛出错误“找不到标签",而“标签"显然在那里 [英] ggplot throws error `label not found`, while `label` is clearly there
问题描述
我可以使用geom_text
绘制以下df
的标签:
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))
但是,当尝试对真实数据使用相同的绘图机制时,会出现错误:
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?
这是我的真实数据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
推荐答案
您的df1
属于cld
和data.frame
类(请参见上述str
的输出中的第二行).似乎ggplot不喜欢该对象首先是cld
.为了解决这个问题,使用as.data.frame
强制df1
仅成为data.frame
类.您可以使用class(df1)
进行检出,或参见下面的str(df1)
输出.注意类"行.
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
如果将其强制为data.frame
,则可以正常工作.
If you coerce it to data.frame
, it works fine.
ggplot(as.data.frame(df1), aes(x = x, y = y, label = label)) +
geom_text()
这篇关于ggplot抛出错误“找不到标签",而“标签"显然在那里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!