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

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

问题描述:

鉴于我有一个包含矩阵数据:创建饼图矩阵从逗号分隔的单元数据

Data

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

我应该怎样在R

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

+3

谨慎...... –

+1

人们通常会通过编写一些代码开始。 –

+0

查看'par(mfrow = c(3,3))'''pie'也许''text' – G5W

下面是做这件事的一种方法:

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