Geom条形图,计数总和不可见

时间:2018-08-13 09:13:50

标签: r ggplot2 geom-bar

我有一个具有51X5结构的数据框标记

structure(list(Tagging = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("CIRCLE CAMPIAGN", 
    "NATIONAL CAMPIAGN"), class = "factor"), Status = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L), .Label = c("Negative", "Positive"), class = "factor"), 
        Month = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 
        3L, 3L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 
        3L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 
        1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L), .Label = c("JUL", 
        "JUN", "MAY"), class = "factor"), Category = structure(c(1L, 
        4L, 6L, 1L, 2L, 4L, 6L, 1L, 2L, 4L, 5L, 6L, 1L, 2L, 4L, 5L, 
        6L, 1L, 2L, 4L, 5L, 6L, 1L, 2L, 4L, 6L, 1L, 4L, 6L, 2L, 3L, 
        4L, 6L, 1L, 2L, 3L, 4L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 
        3L, 4L, 5L, 6L, 6L), .Label = c("Data", "Other", "Roaming", 
        "Unlimited", "VAS", "Voice"), class = "factor"), count = c(3L, 
        2L, 1L, 4L, 5L, 2L, 1L, 2L, 6L, 7L, 2L, 3L, 4L, 9L, 6L, 2L, 
        3L, 3L, 3L, 10L, 2L, 5L, 5L, 5L, 4L, 3L, 1L, 1L, 1L, 2L, 
        1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 4L, 1L, 1L, 3L, 3L, 2L, 
        1L, 1L, 1L, 3L, 4L, 2L)), class = "data.frame", row.names = c(NA, 
    -51L))

我想创建一个条形图(ggplot)以在条形图上显示带有标签的条形图,作为我使用以下代码的类别月份的总和

ggplot(data = tag, aes(x = Tagging, y = count, fill = Status)) +
  geom_col() +
  labs(x = "Tagging", y = "Count", title = "FlyTxt ROI", subtitle = "Statistics") +
  geom_text(aes(label = count), color = "white", size = 3, position = position_stack(vjust = 0.5)) + 
  theme_minimal()+facet_wrap(~Month)

但是我得到的是分割计数值:

帮助,因为我只希望每种状态的计数总和

1 个答案:

答案 0 :(得分:0)

问题是,您在栏中显示的信息是geom_col在所有类别上累积的,但是geom_text却不这样做。 On选项是预先汇总数据(摆脱类别拆分),然后绘制图表。

library(tidyverse)

tag_sum <- tag %>% 
  group_by(Tagging, Status, Month) %>% 
  summarise(count_sm = sum(count))

ggplot(data = tag_sum, aes(x = Tagging, y = count_sm, fill = Status)) +
  geom_col() +
  geom_text(aes(label = count_sm), color = "white", size = 3, 
            position = position_stack(vjust = 0.5)) + 
  facet_wrap(~Month) + 
  labs(x = "Tagging", y = "Count", title = "FlyTxt ROI", subtitle = "Statistics") +
  theme_minimal() 

enter image description here