2017-07-01 44 views
1

鑑於我有一個包含矩陣數據:創建餅圖矩陣從逗號分隔的單元數據

Data

我想創建一個餅圖矩陣。輸出應該是這樣的output

我應該怎樣在R

注意:我希望它能夠將餅圖作爲矩陣的一個元素。

+3

謹慎...... –

+1

人們通常會通過編寫一些代碼開始。 –

+0

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

回答

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