条形图中的ggplot2分组

时间:2017-08-24 11:35:59

标签: r plot ggplot2

我希望获取一个数据集,例如,company1拥有" lenovo"产品和" dell"产品。我想打破这个数据集的每一部分以显示"这些是lenovo客户(lenovo == 1),其中哪些有戴尔产品,或者还有三星产品,或者可能只有联想产品。如果可能的话,我希望将它显示在堆积条形图中,或者以小平面网格显示。 理想图表会将每个产品显示为单个条形图,其中条形图由客户包含的其他产品的数量着色。

例如,如果有100个联想客户,其中20个也有戴尔,25个也有苹果,其中10个有三星,(注意其中一些可能重叠,可能有一个客户有三星< em>和 dell,这将计算在dell的20和samsung的10),酒吧将显示20种颜色为dell,25种颜色为苹果,10种颜色为三星,其余颜色为只是联想没有其他产品。 - 然后这将被戴尔复制,哪些戴尔客户与其他集团有产品等等。

可重现的数据:

a <- paste0("abcd", c(1:185))
dell <- sample(c(1, 0, 0), size = 185, replace = TRUE)
apple <- sample(c(1, 0, 0, 0, 0), size =185, replace = TRUE)
lenovo <- sample(c(1, 0), size = 185, replace = TRUE)
samsung <- sample(c(1, 0), size = 185, replace = TRUE)
df <- data.frame(a, dell, apple, lenovo, samsung)

我已经开始尝试做类似的事情:

ggplot(df, aes(x = Dell)) +
  geom_histogram(stat = 'count', position = "dodge") + 
  geom_text(stat = 'count', aes(label = ..count..), position = position_dodge(width = .9), vjust = -1) +
  scale_y_continuous(labels = comma)

我尝试这样做的另一种方式是数据是逐行的,如果有戴尔,苹果和三星的客户,它们将由3行代表。这样我可以通过产品facet_grid。问题是我很难显示这一行客户abcd1有苹果,还有三星和戴尔,并可视化。

感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

The widyr package旨在获取整洁的数据帧,执行宽矩阵操作并重新整理它。在这里,我首先整理您的数据,创建一个列,每个产品作为行,以及一个列,其中包含每个客户的二进制状态。然后删除“没有”行(hasproduct != 0),并对所有产品进行成对计数。

library(tidyr)
library(widyr)
library(ggplot2)
library(dplyr)

data_frame(a = paste0("abcd", c(1:185)),
           dell = sample(c(1, 0, 0), size = 185, replace = TRUE),
           apple = sample(c(1, 0, 0, 0, 0), size = 185, replace = TRUE),
           lenovo = sample(c(1, 0), size = 185, replace = TRUE),
           samsung = sample(c(1, 0), size = 185, replace = TRUE)) %>% 
  gather(key = product, value = hasproduct, -a) %>% 
  filter(hasproduct != 0) %>% 
  widyr::pairwise_count(product, a, diag = T) %>% 
  ggplot(aes(item1, n, fill = item2)) + 
  geom_col(position = "stack")

enter image description here

如果您不希望计算每个组的大小(拥有Apple产品的Apple用户),请将diag = T更改为diag = F

答案 1 :(得分:0)

这是你指的是第一个吗?如果是这样,请告诉我,我会编辑和解释。

library(tidyverse)
library(rlang)

computers <- c("dell", "apple", "lenovo", "samsung")


all_dfs <-
  map(computers, ~ {
    df %>%
      gather(computer, count, !!.x) %>%
      gather(cat, value, setdiff(computers, !!.x)) %>%
      mutate(cat = ifelse(count == 0, "they use same company", cat))
  }) %>%
  reduce(bind_rows)

all_dfs %>%
  ggplot(aes(computer, fill = cat)) +
  geom_bar()