2017-04-03 156 views
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,它仍然給了我同樣的錯誤。

我在這裏做錯了什麼?

+4

你已經把'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

回答

4

把所有在一起,從評論和進球數,下面

# 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 

代碼加入球隊reodering創建此圖表:

enter image description here

數據

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