R - 多面饼图

R - pie chart in facet

我有四个饼图,我需要将它们全部显示在两行两列中。 我使用下面的脚本来显示一个:

slices <- c(39, 7, 13)
lbls <- c("monthly", "daily", "weekly")
pct <- slices
lbls <- paste(lbls, pct) 
pie(slices,labels = lbls, col=rainbow(length(lbls)),
    main="Purchased Products")

如果其他三个饼图值如下,如何每次创建三个不同主标题的饼图:

slices <- c(40, 5, 12)
lbls <- c("monthly", "daily", "weekly")

slices <- c(15, 27, 47)
lbls <- c("monthly", "daily", "weekly")

slices <- c(58, 47, 2)
lbls <- c("monthly", "daily", "weekly")

类似的东西会起作用。您只需更改数据的格式并使用 tidyverse.

中的 ggplot2
library(tidyverse)

df1 <- expand_grid(pie = 1:4, labels = c("monthly", "daily", "weekly"))
df2 <- tibble(slices = c(39, 7, 13,
                         40, 5, 12,
                         15, 27, 47,
                         58, 47, 2))

# join the data
df <- bind_cols(df1, df2) %>% 
  group_by(pie) %>% 
  mutate(pct = slices/sum(slices)*100) # pct for the pie - adds to 100
  
# graph
ggplot(df, aes(x="", y=pct, fill=labels)) + # pct used here so slices add to 100
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0) +
  geom_text(aes(label = slices), position = position_stack(vjust=0.5)) +
  facet_wrap(~pie, ncol = 2) +
  theme_void() +
  theme(legend.position = "bottom")

使用数据的编辑版本

> df
# A tibble: 12 x 4
# Groups:   pie [4]
     pie labels  slices   pct
   <int> <chr>    <dbl> <dbl>
 1     1 monthly     39    66
 2     1 daily        7    12
 3     1 weekly      13    22
 4     2 monthly     40    70
 5     2 daily        5     9
 6     2 weekly      12    21
 7     3 monthly     15    17
 8     3 daily       27    30
 9     3 weekly      47    53
10     4 monthly     58    54
11     4 daily       47    44
12     4 weekly       2     2