用圆形条形图替换散点图中的 bubbles/points

Replace bubbles/points in scatterplot by circular barplot

在尝试可视化一些数据时,我遇到了在散点图中显示圆形条形图的挑战。

习惯了 ggplot2,我能够绘制圆形条形图、散点图,但无法找到将两者结合起来的方法。

我想用圆形条形图替换散点图中的点。

有什么想法吗?也许是另一个图书馆?

示例代码如下:

library(ggplot2)

df1 <- structure(list(P = c(1L, 1L, 1L, 2L, 2L, 2L),
                      A = c(2L, 2L, 2L, 4L, 4L, 4L),
                      B = c(2L, 2L, 2L, 3L, 3L, 3L), 
                      C = c(1L, 2L, 3L, 1L, 2L, 3L), 
                      D = c(1L, 3L, 1L, 4L, 5L, 1L)),
                 row.names = c(NA,-6L), class = "data.frame")
scatter_plot <- ggplot(df1, aes(x=A, y=B)) +
  geom_point()

circular_barplot <- ggplot(df1, aes(x=C,y=D)) +
  geom_bar(stat="identity") +
  coord_polar(start=0) +
  facet_wrap(~P)

输出:
scatter_plot:

圆形条形图

一种方法是使用 ggforce::geom_arc_bar,它允许在笛卡尔坐标系中添加饼图。请注意,通过下面的代码是一种快速而肮脏的方法,可以为您的示例数据实现您想要的结果。

基本上我首先进行一些数据整理以获得楔形的 startend 以及半径。之后我拆分数据并通过多个 ggforce::geom_arc_bar 添加圆形条。我添加了两个参数 r.max 来设置最大半径和偏移量以设置“条形”之间的“填充”量。

library(ggplot2)
library(ggforce)
library(dplyr)

circular_barplot <- function(.data, r.max = .2, offset = .1) {
  .data <- .data |> 
    mutate(start = (C - 1) * 2 * pi / max(C) + offset,
           end = C * 2 * pi / max(C) - offset,
           r = D / max(D) * r.max)
  .data_split <- split(.data, .data$P)
  
  lapply(.data_split, function(.data) {
    x0 <- unique(.data$A)
    y0 <- unique(.data$B)
    geom_arc_bar(aes(
      x0 = x0, y0 = y0, r0 = 0, r = r, start = start, end = end, fill = factor(C)),
      data = .data
    )  
  })
}

ggplot() +
  circular_barplot(df1) +
  coord_fixed()