使用ggplot2在总计上创建条形图

时间:2018-01-05 17:51:27

标签: r ggplot2

为了避免制作饼图,我想创建一个条形图。但是,我希望显示每个类别的总数。这是我用dput()函数创建的数据集:

df <- structure(list(Status = structure(c(4L, 6L, 1L, 5L, 2L, 3L), .Label = c("Compromise", 
"Launched", "Not yet rated", "Promise broken", "Promise kept", 
"Stuck"), class = "factor"), n = c(15L, 4L, 4L, 7L, 9L, 21L), 
    total = c("60", "60", "60", "60", "60", "60")), .Names = c("Status", 
"n", "total"), row.names = c(NA, -6L), class = c("tbl_df", "tbl", 
"data.frame"))

这是我的ggplot2代码:

df %>%
  ggplot(aes(x = Status, y = n, fill = Status)) +
  geom_col() +
  coord_flip() +
  geom_text(aes(label = n), 
            hjust = 2,
            colour = "white",
            fontface = "bold",
            size = 3) +
  scale_x_discrete(limits = rev(order)) +
  scale_fill_tableau() +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        legend.position = "null")

以下是皮尤研究中心的一个例子(显然有完全不同的数据)来了解我想要实现的目标:

enter image description here

1 个答案:

答案 0 :(得分:0)

您已获得total,只需将其转换为数字并首先添加另一个geom_col图层。

df$total = as.numeric(as.character(df$total))

  ggplot(df, aes(x = Status, y = n, fill = Status)) +
    geom_col(aes(y = total), fill = "grey90") +
    geom_col() +
    coord_flip() +
    geom_text(aes(label = n), 
            hjust = 2,
            colour = "white",
            fontface = "bold",
            size = 3) +
    scale_x_discrete(limits = rev(order)) +
    scale_fill_tableau() +
    theme_minimal() +
    theme(axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        legend.position = "null")