其他
ggplot2绘制美美的月亮图
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「gggibbous」批量绘制月亮图来替代饼图,通过一种新的展示方式来进行数据可视化,下面来看看具体操作
❞
加载R包
library(tidyverse)
library(gggibbous)
library(ggtext)
library(ggfx)
library(showtext)
library(magick)
library(magrittr)
定义字体
showtext_auto()
font_add_google("Karla", "Karla")
font_add_google("Oswald", "Oswald")
导入数据
sunshine <- read_csv('sunshine.csv')
数据清洗
months_order <- c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
selected_cities <- c('Oslo',"Vienna","Brussels","Rome","Milan","Amsterdam","Nicosia",
"Madrid","Edinburgh","Tromsø","Tórshavn")
sunshine %<>%
filter(City %in% selected_cities) %>%
pivot_longer(cols=Jan:Dec,values_to = 'sunshine_hours',names_to = 'month') %>%
mutate(total_hours=case_when(
month=='Feb' ~ 28 * 24,
month %in% c('Jan','Mar','May','Jun','Jul','Aug','Oct','Dec') ~ 31 *24,
TRUE ~ 30 * 24)) %>%
mutate(dark_hours = total_hours - sunshine_hours,
ratio = sunshine_hours / total_hours) %>%
mutate(month = factor(month, levels = months_order)) %>%
mutate(right = TRUE)
数据可视化
g <- sunshine %>%
ggplot() +
geom_moon(aes(1,1,ratio=1),fill='#023047',color='#023047',size=15,alpha=0.9) +
geom_moon(aes(1,1,ratio=1),fill='#e5e5e5',color='#e5e5e5',size=15,alpha=0.3)+
with_outer_glow(geom_moon(aes(1,1,ratio=ratio,right=right),
fill='#fca311',color='#fca311',size=15),color='#fca311')+
geom_text(aes(1,1,label=round(sunshine_hours)),color='grey80',size=3) +
coord_fixed() +
theme_void(base_family='Oswald') +
facet_grid(fct_reorder(City,Year) ~ month,switch="y") +
theme(legend.position="none")
保存数据
ggsave("Figure.pdf",width=12,height=8,device = cairo_pdf)
数据获取
❝本节的内容到此结束,可以看到展示效果还是蛮优雅的,喜欢的小伙伴欢迎转发此文档附上一句话到朋友圈「30分钟后台截图给我」,即可获取对应的数据及代码,如未及时回复可添加我的微信
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐