答案 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)
结果: