本次示例主要学习两个内容,一个是使用ggplot2
画饼图,另一个是把数据转换为百分比样式。
数据 本次绘制的图很简单,主要是为了学习使用ggplot2
绘制饼图及添加百分比形式的标签
首先加载使用到的R包
library (ggplot2)library (ggthemes)
然后看一下数据结构
df2 <- read.csv('./df2.csv' ,header = T )library (dplyr)## ## 载入程辑包:'dplyr' ## The following objects are masked from 'package:stats': ## ## filter, lag ## The following objects are masked from 'package:base': ## ## intersect, setdiff, setequal, union df2_1 <- df2 %>% group_by(年份) %>% mutate(占比 = scales::percent(value / sum(value))) knitr::kable(df2_1)
年份 科室 value 占比 2017 2型糖尿病 72 75.0% 2017 糖尿病肾病 14 14.6% 2017 糖尿病周围神经病变 10 10.4% 2018 2型糖尿病 178 80.5% 2018 糖尿病肾病 11 5.0% 2018 糖尿病周围神经病变 32 14.5% 2019 2型糖尿病 167 71.7% 2019 糖尿病肾病 22 9.4% 2019 糖尿病周围神经病变 44 18.9% 2020 2型糖尿病 249 77.09% 2020 糖尿病肾病 38 11.76% 2020 糖尿病周围神经病变 36 11.15%
画图
p21 <- ggplot(df2_1[1 :3 ,],aes(x='' ,y=value,fill=科室))+ geom_bar(stat = 'identity' ,width = 1 ,position = 'stack' )+ geom_text(aes(y=c(55 ,18 ,5.5 ),label=占比),size=8 )+ scale_y_continuous(expand = c(0 ,0 ))+ theme_bw()+ labs(x=NULL ,y=NULL ,title = '2017年' )+ theme(legend.title = element_blank(), legend.position = 'bottom' , legend.text = element_text(colour = 'black' ,size = 16 ), axis.text = element_blank(), axis.title = element_blank(), panel.border = element_blank(), panel.grid = element_blank(), plot.title = element_text(hjust = 0.5 ,size = 20 ) )+ coord_polar(theta = 'y' , start = 0 , direction = 1 ) p21
百分比样式经常用到,主要是灵活使用scales::percent_format()
和scales::percent()
函数
再看下另一种把坐标轴变成百分比的例子
library (ggplot2)library (ggsci)library (ggthemes) df4 <- read.csv('./df4.csv' ,header = T ) knitr::kable(df4)
year value 2017 0.1503 2018 0.2281 2019 0.4364 2020 0.5916
# 折线图 ggplot(df4,aes(year,value))+ geom_line(size=1.5 )+ geom_point(size=5 ,color='red' )+ geom_text(aes(y=value+0.05 ,label=scales::percent(value,accuracy = 0.01 )),size=5 )+ labs(x=NULL ,y=NULL )+ scale_y_continuous(labels = scales::percent_format(accuracy = 1 ))+ theme(axis.text = element_text(color = 'black' ,size = 16 ), legend.position = 'bottom' , legend.title = element_text(color = 'black' ,size = 16 ), legend.text = element_text(color = 'black' ,size = 16 ) )+ theme_hc()
欢迎大家关注我的公众号:医学和生信笔记
医学和生信笔记 公众号主要分享:1.医学小知识、肛肠科小知识;2.R语言和Python相关的数据分析、可视化、机器学习等;3.生物信息学学习资料和自己的学习笔记!