R GGplot2堆积列表

时间:2016-09-16 19:13:24

标签: r ggplot2

我正在尝试在R中做一个Stacked Columns Chart。抱歉,我正在学习这就是为什么我需要帮助

这就是我拥有数据的方式

structure(list(Category = structure(c(2L, 3L, 4L, 1L), .Label = c("MLC1000", 
    "MLC1051", "MLC1648", "MLC5726"), class = "factor"), Minutes = c(2751698L, 
    2478850L, 556802L, 2892097L), Items = c(684L, 607L, 135L, 711L
    ), Visits = c(130293L, 65282L, 25484L, 81216L), Sold = c(2625L, 
    1093L, 681L, 1802L)), .Names = c("Category", "Minutes", "Items", 
    "Visits", "Sold"), class = "data.frame", row.names = c(NA, -4L)
)

我想创建这个图片

dict

1 个答案:

答案 0 :(得分:1)

我认为应该应用两个非常基本的原则来使这个问题更容易处理。首先,您应该制作数据tidy。其次,你不应该让ggplot为你做计算。

library(tidyverse)

a <- data_frame(
  category = letters[1:4],
  minutes = c(2751698, 2478850, 556802, 2892097),
  visits = c(130293, 65282, 25484, 81216),
  sold = c(2625, 1093, 681, 1802)
) %>%
  gather(variable, value, -category) %>%   # make tidy
  group_by(variable) %>%
  mutate(weight = value / sum(value))   # calculate weight variable

## Source: local data frame [12 x 4]
## Groups: variable [3]
##   category variable   value     weight
##       <chr>    <chr>   <dbl>      <dbl>
## 1         a  minutes 2751698 0.31703610
## 2         b  minutes 2478850 0.28559999
## 3         c  minutes  556802 0.06415178
## 4         d  minutes 2892097 0.33321213
## 5         a   visits  130293 0.43104127
## 6         b   visits   65282 0.21596890
## 7         c   visits   25484 0.08430734
## 8         d   visits   81216 0.26868249
## 9         a     sold    2625 0.42331882
## 10        b     sold    1093 0.17626189
## 11        c     sold     681 0.10982100
## 12        d     sold    1802 0.29059829

我不知道您的structure()是什么,但我无法从中构建数据框而不会导致R会话崩溃。

一旦我们将数据转换为此格式,ggplot2调用实际上非常简单:

ggplot(a, aes(x = variable, weight = weight * 100, fill = category)) +
  geom_bar()

enter image description here

相关问题