复合图形可以给出更多的信息,并且更能够观察数据之间的联系。一般所说的复合饼图包括以下两种:

    散点复合饼图(compound scatter and pie chart)可以展示三个数据变量的信息:(x, y, P),其中x和y决定气泡在直角坐标系中的位置,P表示饼图的数据信息,决定饼图中各个类别的占比情况,如图1(a)所示。

    气泡复合饼图(compound bubble and pie chart)可以展示四个数据变量的信息:(x, y, z, P),其中x和y决定气泡在直角坐标系中的位置,z决定气泡的大小,P表示饼图的数据信息,决定饼图中各个类别的占比情况,如图1(b)所示。
    P1.png
    P2.png

    具体操作如下:

    1. library(ggforce)
    2. library(dplyr)
    3. data_graph <- read.table(text = "x y group nb
    4. 1 0 0 1 1060
    5. 2 0 0 2 361
    6. 3 0 0 3 267
    7. 4 0 1 1 788
    8. 5 0 1 2 215
    9. 6 0 1 3 80
    10. 7 1 0 1 485
    11. 8 1 0 2 168
    12. 9 1 0 3 101
    13. 10 1 1 1 6306
    14. 11 1 1 2 1501
    15. 12 1 1 3 379", header = TRUE)
    16. # make group a factor
    17. data_graph$group <- factor(data_graph$group)
    18. # add case variable that separates the four pies
    19. data_graph <- cbind(data_graph, case = rep(c("Aaaa", "Bbbb", "Cccc", "Dddd"), each = 3))
    20. # calculate the start and end angles for each pie
    21. data_graph <- left_join(data_graph,
    22. data_graph %>%
    23. group_by(case) %>%
    24. summarize(nb_total = sum(nb))) %>%
    25. group_by(case) %>%
    26. mutate(nb_frac = 2*pi*cumsum(nb)/nb_total,
    27. start = lag(nb_frac, default = 0))
    28. # position of the labels
    29. data_labels <- data_graph %>%
    30. group_by(case) %>%
    31. summarize(x = x[1], y = y[1], nb_total = nb_total[1])
    32. # overall scaling for pie size
    33. scale = .5/sqrt(max(data_graph$nb_total))
    34. # draw the pies
    35. ggplot(data_graph) +
    36. geom_arc_bar(aes(x0 = x, y0 = y, r0 = 0, r = sqrt(nb_total)*scale,
    37. start = start, end = nb_frac, fill = group)) +
    38. geom_text(data = data_labels,
    39. aes(label = case, x = x, y = y + scale*sqrt(nb_total) + .05),
    40. size =11/.pt, vjust = 0) +
    41. coord_fixed() +
    42. scale_x_continuous(breaks = c(0, 1), labels = c("X0", "X1"), name = "x axis") +
    43. scale_y_continuous(breaks = c(0, 1), labels = c("Y0", "Y1"), name = "y axis") +
    44. theme_minimal() +
    45. theme(panel.grid.minor = element_blank())

    最终得到的图形如下所示:

    P3.png