While trying to visualise some data, I encountered the challenge to display circular barplots in a scatterplot.
Being used to ggplot2, I'm able to draw circular barplots, a scatterplot, but was not able to find a way to combine both of them.
I'd like to replace the points in the scatterplot, by the circular barplots.
Any ideas? Maybe another library?
Below a sample code:
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)
CodePudding user response:
One approach would be to use ggforce::geom_arc_bar
which allows to add pies in cartesian coordinates. Note that by code below is a quick and dirty approach to achieve your desired result for your example data.
Basically I first do some data wrangling to get the start
and end
for the wedges as well as the radius. Afterwards I split the data and add the circular bars via multiple ggforce::geom_arc_bar
s. I added two parameters r.max
to set maximum radius and offset to set the amount of "padding" between the "bars".
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()