在嘗試可視化一些資料時,我遇到了在散點圖中顯示圓形條形圖的挑戰。
習慣了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)
輸出:
散點圖:

圓形條形圖

uj5u.com熱心網友回復:
一種方法是使用ggforce::geom_arc_bar允許在笛卡爾坐標中添加餅圖。請注意,通過下面的代碼是一種快速而骯臟的方法,可以為您的示例資料實作您想要的結果。
基本上,我首先進行一些資料整理以獲得楔形和半徑的start和end。之后我拆分資料并通過多個ggforce::geom_arc_bars 添加圓形條。我添加了兩個引數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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/466740.html
