分享

R语言ggplot2画饼图及添加百分比标签

 阿越就是我 2023-10-12 发布于上海

本次示例主要学习两个内容,一个是使用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占比
20172型糖尿病7275.0%
2017糖尿病肾病1414.6%
2017糖尿病周围神经病变1010.4%
20182型糖尿病17880.5%
2018糖尿病肾病115.0%
2018糖尿病周围神经病变3214.5%
20192型糖尿病16771.7%
2019糖尿病肾病229.4%
2019糖尿病周围神经病变4418.9%
20202型糖尿病24977.09%
2020糖尿病肾病3811.76%
2020糖尿病周围神经病变3611.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)
yearvalue
20170.1503
20180.2281
20190.4364
20200.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.生物信息学学习资料和自己的学习笔记!

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多