尝试使用ggplot向条形图添加数据标签时,出现以下错误:
Error: geom_text requires the following missing aesthetics: x
我的示例数据如下:
| Team | Goals |
|------------ |------- |
| Manchester | 26 |
| Liverpool | 25 |
| Man City | 30 |
| Chelsea | 32 |
| Arsenal | 11 |
| West Ham | 22 |
| Stoke | 23 |
这里是我用来创建条形图的代码。
g<- ggplot(data = scores) +
geom_bar(mapping = aes(x=Team, y=Goals, color = Team, fill = Team),
stat = "identity")
g <- g + ggtitle("Goals per Team") + ylab("Number of Goals")
g <- g + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5))
g + geom_text(aes(y=Goals, label=Goals))
g
即使我在
g + geom_text(aes(x = Team, y=Goals, label=Goals))
中添加了 x = Team
,它仍然给出相同的错误信息。我做错了什么?
geom_bar
中,您将x=Team
放在里面,所以geom_text
不知道它。如果您希望一个美学应用于所有几何对象,请将其放在对ggplot
的主要调用中。例如,在您的情况下,执行ggplot(data=scores, aes(x=Team, y=Goals))
,然后您就不需要在geom_bar
或geom_text
中再次提及这些映射。如果您希望文本标签也映射到颜色,则还应在ggplot
的主要调用中包含colour=Team
。 - eipi10