【发布时间】:2017-04-03 05:08:47
【问题描述】:
尝试将数据标签添加到条形图,使用 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,它仍然给我同样的错误。
我在这里做错了什么?
【问题讨论】:
-
你把
x=Team放在geom_bar里面,所以geom_text不知道。如果您想将美学应用于所有几何图形,请将其放在对ggplot的主要调用中。例如,在您的情况下,请执行ggplot(data = scores, aes(x=Team, y=Goals)),然后您无需在geom_bar或geom_text中再次提及这些映射。如果您希望文本标签也映射到颜色,那么在对ggplot的主要调用中也包含colour=Team。