常见的热图看腻了,这节来介绍如何通过ggplot2绘制圆形热图,为了方便各位观众老爷观看,我制作了一个交互式文档,后台回复关键词2021-4-14获取本文代码及文档 (这个是我转载的推文,如果需要这个代码和数据,需要到原公众号去留言)
加载R包
代码语言:javascript复制library(tidyverse)
library(ggthemes)
library(cowplot)
读入数据
代码语言:javascript复制accidents <- read.csv("accidents.txt") %>%
mutate(Year=as.numeric(Year)) %>% as_tibble()
代码语言:javascript复制> accidents
# A tibble: 156 x 3
Year Deaths Month
<dbl> <int> <int>
1 2007 126 1
2 2007 105 2
3 2007 133 3
4 2007 137 4
5 2007 128 5
6 2007 108 6
7 2007 170 7
8 2007 143 8
9 2007 146 9
10 2007 145 10
数据可视化
先画一张常见的热图
代码语言:javascript复制ggplot(accidents, aes(x=Month, y=Year, fill=Deaths))
geom_tile(colour="white")
scale_fill_gradient(low = "white", high = "#c85c32") -> p1
p1
更改刻度范围
代码语言:javascript复制p1 xlim(-11,13) ylim(2000,2020) -> p2
p2
转换为极坐标
代码语言:javascript复制p2 coord_polar(theta = "x", start = pi/3) -> p3
p3
修改主题
代码语言:javascript复制 p3 theme(panel.background=element_rect(fill = "white"),
axis.title=element_blank(),
panel.grid=element_blank(),
axis.text.x = element_blank(),
axis.ticks=element_blank(),
axis.text.y=element_blank(),
legend.position = c(0.48,0.52),
legend.direction = "vertical",
legend.background = element_blank(),
legend.text = element_text(size = 8)) -> p4
p4
geom_text添加文本
代码语言:javascript复制p4 geom_text(aes(x=12.5, y=Year, label=Year),hjust=-0.2,
size=2.5, angle= -53,
inherit.aes = FALSE)
geom_text(aes(x=1, y=2020, label="1"),
hjust=0.5, vjust = 0,size=3,
angle= 120, inherit.aes = FALSE)
geom_text(aes(x=11, y=2020, label="11"),
hjust=0.5, vjust = 0,size=3,
angle=-30, inherit.aes = FALSE)
geom_text(aes(x=12, y=2020, label="12"),hjust=0.5, vjust = 0,
size=3, angle= -44, inherit.aes = FALSE )
geom_text(aes(x=10, y=2020, label="10"),
hjust=0.5, vjust = 0,size=3,
angle=-18, inherit.aes = FALSE)
geom_text(aes(x=9, y=2020, label="9"),
hjust=0.5, vjust = 0,size=3,
angle=5, inherit.aes = FALSE)
geom_text(aes(x=8, y=2020, label="8"),hjust=0.5, vjust = 0,
size=3, angle= 18, inherit.aes = FALSE )
geom_text(aes(x=7, y=2020, label="7"),
hjust=0.5, vjust = 0,size=3,
angle=31, inherit.aes = FALSE)
geom_text(aes(x=6, y=2020, label="6"),
hjust=0.5, vjust = 0,size=3,
angle=44, inherit.aes = FALSE)
geom_text(aes(x=5, y=2020, label="5"),hjust=0.5, vjust = 0,
size=3, angle= 70, inherit.aes = FALSE )
geom_text(aes(x=4, y=2020, label="4"),hjust=0.5, vjust = 0,
size=3, angle= 80, inherit.aes = FALSE )
geom_text(aes(x=3, y=2020, label="3"),hjust=0.5, vjust = 0,
size=3, angle= 90, inherit.aes = FALSE )
geom_text(aes(x=2, y=2020, label="2"),hjust=0.5, vjust = 0,
size=3, angle= 110, inherit.aes = FALSE )
guides(fill = guide_colourbar(barheight = 2.5, barwidth = 1,
ticks= F,title.position = "left",
title.theme = element_text(size = 12, angle = 90),
label.theme = element_text(size = 7)))