【问题标题】:How to Add Data Labels to ggplot如何将数据标签添加到 ggplot
【发布时间】: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_bargeom_text 中再次提及这些映射。如果您希望文本标签也映射到颜色,那么在对 ggplot 的主要调用中也包含 colour=Team

标签: r ggplot2 bar-chart


【解决方案1】:

将评论中的所有内容放在一起并按目标数量添加团队重新排序,代码如下

# 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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-04
    • 2023-03-16
    • 2017-09-10
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多