ggplot2优雅的绘制发光点图

2023-09-11 08:53:37 浏览数 (1)

❝本节来介绍如何使用「ggplot2结合ggfx」来绘制发光点图,下面小编通过一个案例来进行展示,图形仅供展示用,希望各位观众老爷能够喜欢。❞

加载R包

代码语言:javascript复制
library(tidyverse)
library(janitor)
library(ggtext)
library(ggforce)
library(ggfx)

导入数据

代码语言:javascript复制
df <- read_tsv("data.tsv")

定义调色板

代码语言:javascript复制
pal <- c('#ecbf3d', '#f0cc46', '#f5e355', '#fdf56d', '#fdffbe', '#ffffff')

数据清洗

代码语言:javascript复制
cities <- c("Paris", "Berlin", "London", "Sydney", "New York")

df_time <- df %>% 
  group_by(zone) %>%  # 按时区分组
  slice_max(end) %>%  # 选择每组的最大值
  mutate(city = str_replace(str_extract(zone, "(?<=/)[^/]*$"), "_", " ")) %>%  # 提取并替换城市名
  filter(city %in% cities) %>%  # 过滤出指定城市
  mutate(
    city = factor(city, levels = rev(cities)),  # 将城市转换为因子变量
    lab = paste0(city, "."),  # 创建标签
    offset = offset/3600,  # 转换时区偏移量
    offset_lab = ifelse(offset < 0, as.character(offset), paste0(" ", offset))  # 创建时区标签
  ) %>% 
  ungroup()  # 取消分组

构建圆形数据框

代码语言:javascript复制
df_circle <- map_dfr(cities, ~{
  tibble(x = 0,y = 0,
    r = seq(1, 0.75, length = 10),
    col = colorRampPalette(pal)(10),
    city = .x)
}) %>% 
  mutate(city = factor(city, levels = rev(cities))) %>%  # 将城市转换为因子变量
  left_join(df_time %>% select(city, offset),by = "city") %>%  # 左连接
  mutate(y = as.numeric(city))  # 转换城市为数值型

数据可视化

代码语言:javascript复制
df_time %>% ggplot()  
  geom_text(aes(0, city, label = lab),size =5, colour = ifelse(df_time$dst,"#ecbf3d", "white"),
            hjust = 0, fontface = "bold")    # 添加城市标签
  geom_text(aes(3.8, city, label = offset_lab), colour = "white", size = 4, fontface = "bold")    # 添加时区标签
  geom_segment(aes(x=4, xend = 8, y = city, yend = city), colour = "white")    # 添加线段
  with_inner_glow(
    geom_circle(aes(x0 = offset/6 6, y0 = y, r = r/2, fill = col, group = city), df_circle, colour = NA),
    colour = "grey20", expand = 2, sigma = 5)    # 添加带内部发光的圆形
  scale_fill_identity()    # 使用原始填充色
  coord_fixed()    # 固定坐标轴
  theme_void()    # 使用空白主题
  theme(plot.background = element_rect(fill ="grey20", colour = "grey20"),  # 设置背景色
    plot.margin = margin(b = 2, t = 5, r = 5, l = 5))  # 设置边距

0 人点赞