其他
ggplot2优雅的给传统气泡图添加新元素
欢迎关注R语言数据分析指南
❝本节来介绍如何使用ggplot2来给常见的气泡图添加一点新的元素,下面通过1个案例来进行展示;数据及代码已经上传小编的VIP群,
❞有需要的观众老爷欢迎加入小编的VIP群
,目前已经上传「公众号文档数据+代码约170余篇」,扫描文末尾二维码加小编微信「付费99元」后邀请进群,「由于群名额有限人满之后将不在添加新成员」,有需要的请尽早加入,早进早享受,如果对加群没兴趣的观众老爷可在文末找到获取数据的方式
加载R包
library(tidyverse)
数据清洗
df %>% read_csv('data.txt') %>%
mutate(CL = 8 - CL,
PR = 8 - PR) %>%
filter(year %in% c(1995,2020)) %>%
group_by(country) %>%
mutate(gap_cl = CL - lag(CL),
gap_pr = PR - lag(PR)) %>%
ungroup() %>%
filter(!is.na(gap_cl), !is.na(gap_pr))
定义文本与刻度条信息
由于需要绘制刻度条并添加文本因此在此我们需要定义两个数据集
seg_size <- 0.01
seg_cl <- tibble(x = seq(0.8,7.2,seg_size),
xend = seq(0.8,7.2,seg_size),
y = rep(-0.1, 6.4/seg_size +1),
yend = rep(-0.4, 6.4/seg_size +1)) %>%
mutate(color = x^2)
seg_pr <- tibble(x = rep(0-0.1, 6.4/seg_size +1),
xend = rep(-0.4, 6.4/seg_size +1),
y = seq(0.8,7.2,seg_size),
yend = seq(0.8,7.2,seg_size))%>%
mutate(color = y^2)
seg <- bind_rows(seg_cl, seg_pr)
signs <- tibble(x = c(-0.25, -0.25, 1.25, 6.75),
y = c(1.25, 6.75, -0.25, -0.25),
text = c("-", "+", "-", "+"))
数据可视化
df %>%
filter(!is.na(gap_cl)) %>%
count(CL, PR) %>%
arrange(n) %>%
mutate(prod = CL * PR) %>%
ggplot() +
scale_color_gradientn(colours = rev(RColorBrewer::brewer.pal(11,"RdBu")))+
geom_point(aes(CL, PR, size = n, color = prod)) +
geom_text(aes(CL, PR,label = n), size = 4,fontface = "bold")+
geom_segment(data = seg, aes(x = x, xend = xend, y = y, yend = yend, color = color))+
geom_text(data = signs, aes(x = x, y = y, label = text),size = 5, fontface = "bold")+
annotate("text", x = 4, y = -0.25,
label = "Civil Liberties", size = 4, fontface = "bold") +
annotate("text", x = -0.25, y = 4,
label = "Political Rights",size = 4, fontface = "bold", angle = 90) +
scale_size(range= c(5, 25)) +
guides(color = "none", size = "none") +
theme_void()+
theme(plot.background = element_rect(fill="Aliceblue",color="Aliceblue"),
plot.margin = unit(c(0.2,0.5,0.2,0.2),"cm"))
数据获取
❝本节介绍到此结束,可以看到一个基础的气泡图根据数据添加了横纵轴刻度条后还是别有一番特色,「有需要获取本篇数据的欢迎转发此文档到朋友圈,30分钟后公众号后台截图给小编」,添加小编微信时请备注来意以便高效处理,「当然更加推荐加入小编的VIP交流群」,绝让你体会到物超所值
❞
小编微信
关注下方公众号下回更新不迷路
往期推荐