❝本节来介绍如何使用「ggplot2结合ggforce」来绘制别具一格的条形图,下面小编通过一个案例来进行展示,图形仅供展示用,希望各位观众老爷能够喜欢。❞
library(tidyverse)
library(ggtext)
library(ggforce)
df <- read_tsv("data.tsv")
# 定义一些常量,用于后续的图形绘制
r <- .275 # 圆的半径
xo <- 115 / 10 # 圆心的 x 坐标
yo <- -0.15 # 圆心的 y 坐标
df %>% ggplot() +
# 使用 facet_wrap 函数按照 'holder_company_name' 进行分面(子图)
facet_wrap(vars(holder_company_name), ncol = 1) +
# 使用 geom_rect 添加一个矩形区域作为背景
geom_rect(aes(xmin = 0, xmax = n / 10, ymin = -.125, ymax = 1.125), fill = "#add8e6", alpha = .65) +
geom_text(aes(x = 95 / 10, y = .5, label = holder_company_name), color = "white", fontface = "bold", size = 4, hjust = 1) +
# 使用 annotate 函数添加多个白色矩形和线段进行装饰
annotate(geom = "rect", xmin = 0, xmax = 100 / 10, ymin = -.125, ymax = 1.125, color = "white", fill = NA) +
annotate(geom = "rect", xmin = -5 / 10, xmax = 0, ymin = .35, ymax = .65, color = "white", fill = "white") +
annotate(geom = "rect", xmin = -7 / 10, xmax = -5 / 10, ymin = .15, ymax = .85, color = "white", fill = "white") +
annotate(geom = "rect", xmin = 100 / 10, xmax = 101 / 10, ymin = .35, ymax = .65, color = "white", fill = "white") +
annotate(geom = "rect", xmin = 101 / 10, xmax = 102 / 10, ymin = .4, ymax = .6, color = "white", fill = "white") +
annotate(geom = "segment", x = 102 / 10, xend = 115 / 10, y = .5, yend = .5, color = "white") +
# 使用 ggforce::geom_circle 添加一个圆形
ggforce::geom_circle(data = tibble(x = xo, y = yo), aes(x0 = xo, y0 = yo, r = r), color = "white", fill = "#add8e6", alpha = .65, size = .85) +
geom_text(aes(x = xo, yo, label = n), size = 3) + # 在圆形中添加文本
theme_minimal() + # 应用图形主题
theme(
text = element_text(color = "white"),
axis.title = element_blank(),
axis.text = element_blank(),
strip.text = element_blank(),
panel.spacing.y = unit(.125, "cm"),
panel.grid = element_blank(),
plot.background = element_rect(fill = "grey20", color = NA),
plot.margin = margin(t = .5, r = 1.5, b = .5, l = 1.5, unit = "cm")
)