📜  ggalluvial ggplot 标签 (1)

📅  最后修改于: 2023-12-03 15:15:15.590000             🧑  作者: Mango

ggalluvial ggplot 标签介绍

简介

ggalluvial ggplot 标签是基于ggplot2包的一个扩展包,用于绘制分类数据的流图,同时拥有美观、灵活等特点,在数据可视化中得到了广泛的应用。

安装

安装ggalluvial ggplot标签:

install.packages("ggalluvial")
基本语法
准备数据
library(ggalluvial)
data(movies)

movies_long<- pivot_longer(movies, -Genre, names_to = "Release Year", values_to = "Movies")
movies_long$Genre <- as.character(movies_long$Genre)
movies_long$`Release Year` <- as.character(movies_long$`Release Year`)
绘制基本图形
ggplot(data = movies_long, aes(x = `Release Year`, stratum = Genre, y = Movies, alluvium = FILL)) +
  geom_flow(color = "darkgray", aes(fill = Genre)) +
  geom_stratum(width = 1/4, fill = "white", color = "darkgray", size = 0.25, aes(label = after_stat(stratum))) +
  geom_text(stat = "stratum", aes(label = stratum), size = 3) +
  theme_void() +
  labs(title = "Movie Genres by Year", subtitle = "Data from IMDb") +
  scale_fill_viridis_d() +
  guides(fill = guide_legend(title = "Genre", nrow = 2))
参数说明
  • aes: 定义图像的数据映射
  • x: x轴变量
  • stratum: 纵向的分类变量
  • y: 流向的数量
  • alluvium: 是否要使用流的呈现方式
  • geom_flow: 画流,color:流的颜色,fill:要传入后续颜色的数据
  • geom_stratum:填充颜色所在的横向块
  • after_stat: 字符串函数,返回一个特定的变量,在 strata 名称后面添加了所属的百分比
  • stat:在字符串之间进行切换,但保留容器的大小
  • guide_legend: 设置图例参数
theme_void()

去除主题元素

labs(title = "Movie Genres by Year", subtitle = "Data from IMDb")

设置标题和副标题

scale_fill_viridis_d()

设置填充颜色

例子
ggplot(data = movies_long, aes(x = Director, stratum = Genre, alluvium = T, fill = Genre)) +
  geom_flow(stat = "alluvium",lode.guidance = "frontback", color = "darkgray") +
  geom_stratum(width = 1/4, fill = "white", color = "darkgray", size = 0.25, aes(label = after_stat(stratum))) +
  geom_text(stat = "stratum", aes(label = stratum), size = 3) +
  theme_void() +
  labs(title = "Movie Directors by Genre", subtitle = "Data from IMDb") +
  scale_fill_viridis_d() +
  guides(fill = guide_legend(title = "Genre", nrow = 2))
综合举例
library(tidyverse)
library(ggalluvial)

# 准备数据
data(movies)
movies_long <- pivot_longer(movies, -Genre, names_to = "Release Year", values_to = "Number of Movies")

# 绘制ggplot图
ggplot(data = movies_long, aes(x = `Release Year`, stratum = Genre, y = `Number of Movies`, alluvium = TRUE, fill = `Release Year`)) +
  
  # 画流出图形 (alluvial) 
  geom_flow(stat = "alluvium", lode.guidance = "frontback", color = "darkgray") +
  
  # 设置锚点块的宽度和样式
  geom_stratum(width = 1/3, fill = "#f0f0f0", color = "darkgray", size = 0.25, aes(label = after_stat(stratum))) +
  
  # 设置锚点块中的显示文字与坐标轴的距离
  geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 4, hjust =-0.5) +
  
  # 设置主题
  theme_void() +
  
  # 设置标题和副标题
  labs(title = "Movie Release and Demographics by Genre", subtitle = "Data from IMDb") +
  
  # 设置填充颜色
  scale_fill_viridis_d() +
  
  # 设置图例参数
  guides(fill = guide_legend(title = "Release Year", nrow = 2))
结论

ggalluvial ggplot 标签可使数据可视化更加美观和清晰,易于理解和解释,具有很好的应用价值。