使用ggplot2在总计之上创建条形图 [英] Create bar chart on top of totals with ggplot2

查看:52
本文介绍了使用ggplot2在总计之上创建条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

To avoid making a pie chart I want to create a barchart. I do however want to show the total for each catagory. Here's my dataset created with dput() function:

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代码:

Here's my ggplot2 code:

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

这是皮尤研究中心的一个示例(显然数据完全不同),以了解我要完成的工作:

And here's an example from pew research center (obviously with totally different data) to get an idea of what I try to accomplish:

推荐答案

您已经获得了 total ,只需将其转换为数字并添加另一个 geom_col 层优先.

You've got the total, you just need to convert it to numeric and add another geom_col layer first.

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

这篇关于使用ggplot2在总计之上创建条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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