将数据框转换为堆积的百分比条形图

时间:2019-03-31 02:32:31

标签: r

我正在尝试将以下数据框转换为百分比堆叠的条形图。数据框(df)如下所示:

enter image description here

我希望有2个小节,一个在前,一后在后,每个堆叠的小节都被接受,拒绝和取消。

2 个答案:

答案 0 :(得分:0)

这是一种使用您的数据获取百分比堆积条形图的通用方法(之所以归类,是因为我不确定您在上面的评论中指出的确切要求):

require(tidyverse)
df %>% gather("var", "val", before, after) %>% 
ggplot(aes(x=var, y=val,fill=type)) + 
  geom_bar(stat="identity",position="fill")

这给您-是您要找的东西吗?

enter image description here

答案 1 :(得分:-1)

恕我直言,accepted answer可以进行改进以更好地反映OP数据的结构

  1. 通过保留列beforeafter
  2. 的顺序
  3. 通过保留行的给定顺序。

要实现此目的,有两种选择:

  • 将类别变量转换为水平按所需顺序排列的因子
  • 或在使用scale_discrete()进行绘图时指定所需的顺序。

下面的代码使用两种技术:

library(ggplot2)
library(tidyr)
library(dplyr)
df %>%
  mutate(type = forcats::fct_inorder(type)) %>%   # preserve row order
  gather("var", "share", before, after) %>%
  ggplot(aes(x = var, y = share, fill = type)) +
  geom_col(position = "fill") +
  scale_x_discrete(limits = c("before", "after"), name = NULL) +   # specify column order
  scale_y_continuous(labels = scales::percent)

以产生图形形式的OP数据:

enter image description here

此外,geom_col()用作geom_bar(stat = "identity")的快捷方式,并且y轴已正确标记。

数据

由于OP没有提供可复制的数据集,而是发布了数据的图像,因此我使用了在线OCR服务将屏幕截图转换为文本。 (出于完整性考虑:如果已搜索“ online ocr”并随机选择https://www.newocr.com/,而这恰好在一开始就产生了所需的结果)。

然后,将OCR结果复制到下面的代码段中:

df <- readr::read_table2(
"type before after
january 297 237
february 182 67
march 234 34
april 55 117")
相关问题