來(lái)源:南丁格爾玫瑰圖
南丁格爾玫瑰圖的本質(zhì)是直條圖艾蓝,主要用在分類(lèi)變量可視化浊竟。想像一下把直條圖的x軸卷成一個(gè)圈谆棱,再把直條圖之間的間隙變小,就成了漂亮的南丁格爾玫瑰圖了嗓违。
1. 加載包
library(dplyr)
library(ggplot2)
2. 生成數(shù)據(jù)
set.seed(1234)
temp0=data.frame(city=LETTERS[1:26],patients=round(rnorm(26,100,20),0))
生成的數(shù)據(jù)包含兩個(gè)變量,分別是city和patients。
3. 數(shù)據(jù)預(yù)處理
temp1=temp0[order(temp0$patients),]
%>% mutate(city=factor(city,levels = city), id=seq(1,26,1),label=paste0(city,sep=" ",patients))
關(guān)于mutate函數(shù)和%>%在之前的推文有介紹缺虐,有疑問(wèn)的伙伴可以自行查看:
總結(jié) | 功能強(qiáng)大的dplyr 包(一)(必學(xué))
數(shù)據(jù)清洗神器之dplyr包(二)
4. 繪制直條圖(geom_col與geom_bar都能繪制直條圖,詳見(jiàn)幫助文件)
p<-ggplot(temp1, aes(id,patients, fill =id,label=label)) +
geom_col(width = 1, color = 'white') +
geom_col(aes(y = I(30)), width = 1, alpha = 0.5, fill = 'white') + #這里其實(shí)是為了方便后面極坐標(biāo)轉(zhuǎn)換時(shí)中間挖空
geom_col(aes(y = I(15)), width = 1, alpha = 0.2, fill = 'white') +
geom_col(aes(y = I(10)), width = 1, color = 'white', fill = 'white')
p
5. 坐標(biāo)軸轉(zhuǎn)換與圖形調(diào)整
p1 <- p+
coord_polar() + #極坐標(biāo)轉(zhuǎn)換礁凡,默認(rèn)順時(shí)針排序
theme_void() + #去掉背景
theme(legend.position="none")+ #去掉圖例
scale_fill_gradientn(colors = c("darkgreen", "green", "orange", "red","firebrick")) #顏色填充
p1
6. 添加標(biāo)簽
p1 + geom_text(data = . %>% filter(between(id,18,26)),nudge_y = -13,size=2.8,color = "white") + #設(shè)置標(biāo)簽的文字的位置和大小
geom_text(data = . %>% filter(between(id,10,17)),nudge_y = 5,color = "black",size=2.5)+
geom_text(data = . %>% filter(between(id,1,10)),nudge_y = 7,color = "black",size=2.3)
今天的學(xué)習(xí)就到這里高氮,希望對(duì)大家有幫助!