1
试图将数据标签添加到barplot,使用ggplot是给我下面的错误:如何添加数据标签到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 |
而且这里是我用来创建一个barplot的代码。
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'不知道它。如果你想要一个审美适用于所有的geom,把它放在'ggplot'的主要调用中。例如,在你的情况下,执行'ggplot(data = scores,aes(x = Team,y = Goals))',然后你不需要在'geom_bar'或'geom_text'中再次提到这些映射。如果您希望文本标签也被映射为颜色,那么在main调用中将'color = Team'也包含在'ggplot'中。 – eipi10