欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2结合ggbeeswarm」来自定义函数批量绘制蜂窝图,下面小编通过一个案例来进行展示,图形仅供展示用,希望各位观众老爷能够喜欢。数据代码已经整合上传到2023VIP交流群,加群的观众老爷可自行下载,有需要的朋友可关注文末介绍加入VIP交流群
❞
关注下方公众号下回更新不迷路
加载R包
library(tidyverse)
library(janitor)
library(glue)
library(ggtext)
library(forcats)
library(ggbeeswarm)
library(emojifont)
导入数据
df <- read_tsv("data.tsv")
定义颜色调色板
pal <- c("#7B2CBF", "#953B98", "#AF4A72", "#CA5A4C", "#E46926", "#FF7900")
bright <- c("#540d6e", "#ee4266", "#ffd23f", "#3bceac")
数据清洗
df_mean <- df %>%
group_by(type) %>%
summarise(n_artists = sum(artists_n, na.rm = TRUE)) %>%
ungroup() %>%
mutate(p_mean = n_artists/sum(n_artists)) %>%
select(type, p_mean)
df_base <- artists %>%
group_by(type, state) %>%
summarise(
n_artists = sum(artists_n, na.rm = TRUE),
lq = sum(log(location_quotient)*artists_n/sum(artists_n, na.rm = TRUE), na.rm = TRUE)) %>%
filter(is.finite(lq)) %>%
group_by(state) %>%
mutate(p = n_artists/sum(n_artists)) %>%
ungroup() %>%
mutate(lab = type,type = as.numeric(fct_reorder(type, lq, median)))
定义绘图函数
make_plot <- function(.state, .x) {
# 筛选特定州的数据
df_state <- df_base %>%
filter(state == .state)
数据可视化
df_base %>%
ggplot(aes(type,lq)) +
geom_text(aes(type, -4, label = str_wrap(lab, 25)), df_state,
size = 20, colour = "grey20", hjust = 0, lineheight = 0.3, vjust = 0.5) +
geom_beeswarm(size = 4, alpha = 0.5, colour = "grey40") +
geom_point(aes(x, y), tibble(x = 1:13, y = 0), colour = "grey20", size = 3) +
geom_point(aes(type, lq), df_state, size = 6, colour = .x) +
annotate("text", y = -1.2, x = 14, label = "Less than the national share",size = 12, colour = "grey20") +
annotate("text", y = 1.2, x = 14, label = "More than the national share",size = 12, colour = "grey20") +
scale_y_continuous(breaks = log(c(0.1, 0.25, 0.5, 1, 2, 4, 8)),
labels = round(c(0.1, 0.25, 0.5, 1, 2, 4, 8), 1)) +
coord_flip(clip = "off") +
theme_void() +
labs(y = "Location Quotient (log scale)") +
theme(text = element_text(colour = "grey20", size = 36),
plot.background = element_rect(fill = "white"),
plot.margin = margin(t = 30, b = 10, l = 30, r = 30),
axis.text.x = element_text(),
axis.title.x = element_text(margin = margin(t = 10)))
# 保存图像
ggsave(glue("plot/artists-{.state}.png"), height = 12, width = 8.5)
}
绘制单个图
make_plot("California", pal[6])
批量绘图
states <- c("South Dakota", "District of Columbia", "Nevada", "New York")
walk2(states, bright, make_plot)
❝本节内容介绍到此结束,有需要学习个性化数据可视化的朋友,欢迎到小编的「淘宝店铺」 「R语言数据分析指南」购买「2023年度会员文档」同步更新中「售价149元」,内容主要包括各种「高分论文的图表分析复现以及一些个性化图表的绘制」均包含数据+代码;按照往年数据小编年产出约在150+以上
❞
购买后微信发小编订单截图即邀请进新的会员交流群,小编的文档为按年售卖,只包含当年度的「除系列课程外」的文档,有需要往年文档的朋友也可下单购买,需要了解更多信息的朋友欢迎交流咨询。
淘宝扫一扫
2023会员群案例展示










