如何将数据标签添加到ggplot [英] How to Add Data Labels to ggplot

查看:403
本文介绍了如何将数据标签添加到ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用ggplot将数据标签添加到barplot会给我以下错误:

Attempting to add data labels to a barplot, using ggplot is giving me the following error:

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的代码.

And here is the code I am using to create a 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,它仍然会给我同样的错误.

Even when I add x = Team in g + geom_text(aes(x = Team, y=Goals, label=Goals)), it still gives me the same error.

我在做什么错了?

推荐答案

从注释中汇总所有内容,并按目标数(以下代码)添加对团队的重新推荐

Putting all together from the comment and adding reodering of teams by number of goals, the code below

# add on: reorder teams by number of goals
scores$Team <- with(scores, reorder(Team, -Goals))
g <- ggplot(scores, 
            # keep all aesthetics in one place
            aes(x = Team, y = Goals, color = Team, fill = Team, label = Goals)) +
  # replacement of geom_bar(stat = "identity")
  geom_col() +
  # avoid overlap of text and bar to make text visible as bar and text have the same colour 
  geom_text(nudge_y = 1) + 
  # alternatively, print text inside of bar in discriminable colour
  # geom_text(nudge_y = -1, color = "black") + 
  ggtitle("Goals per Team") + 
  xlab("Team") + ylab("Number of Goals") +
  theme_bw() + theme(legend.position = "none") + 
  theme(plot.title = element_text(hjust = 0.5))
g

创建此图表:

scores <- structure(list(Team = structure(c(3L, 4L, 2L, 1L, 7L, 6L, 5L), .Label = c("Chelsea", 
"Man City", "Manchester", "Liverpool", "Stoke", "West Ham", "Arsenal"
), class = "factor", scores = structure(c(-11, -32, -25, -30, 
-26, -23, -22), .Dim = 7L, .Dimnames = list(c("Arsenal", "Chelsea", 
"Liverpool", "Man City", "Manchester", "Stoke", "West Ham")))), 
    Goals = c(26L, 25L, 30L, 32L, 11L, 22L, 23L)), .Names = c("Team", 
"Goals"), row.names = c(NA, -7L), class = "data.frame")

这篇关于如何将数据标签添加到ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆