从逗号分隔的单元格数据创建饼图矩阵

时间:2017-07-01 00:16:01

标签: r csv matrix data-visualization pie-chart

鉴于我有包含数据的矩阵:

Data

我想创建一个饼图矩阵。输出应该像这样output

我应该如何进行 R

注意:我希望它将饼图作为矩阵的一个元素。

1 个答案:

答案 0 :(得分:3)

这是实现目标的一种方式:

library(stringr)   # to split strings
library(tidyverse) # to unnest lists of numbers
library(ggplot2)   # for graphs
library(dplyr)     # for pretty code

# Define your matrix
mat <- matrix(c(NA, "1,2,3", "6,7,1", "1,2,3", NA, "8,5,2", "6,7,1", "8,5,2", NA), 
              nrow=3, 
              ncol=3,
              dimnames = list(c("P1", "P2", "P3"), c("P1", "P2", "P3"))) 

mat %>%
  # Convert matrix to a data frame
  as.table() %>%
  as.data.frame() %>%
  # Extract/parse numbers from strings (e.g. "1,2,3")
  mutate(Freq = str_split(Freq,",")) %>%
  unnest(Freq) %>%
  mutate(Freq = as.integer(Freq)) %>%
  # Convert the values to a percentage (which adds up to 1 for each graph)
  group_by(Var1, Var2) %>%
  mutate(Freq = ifelse(is.na(Freq), NA, Freq / sum(Freq)),
         color = row_number()) %>%
  ungroup() %>%
  # Plot
  ggplot(aes("", Freq, fill=factor(color))) + 
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y") +       # Make it a pie chart
  facet_wrap(~Var1+Var2) + # Break it down into 9 charts
  # Below is just aesthetics
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        axis.title = element_blank()) +
  guides(fill = FALSE)

结果:

enter image description here