前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ggplot2轻松绘制误差线点图与箱线图

ggplot2轻松绘制误差线点图与箱线图

作者头像
R语言数据分析指南
发布2023-08-18 13:34:49
3530
发布2023-08-18 13:34:49
举报

欢迎关注R语言数据分析指南

❝最近群里有朋友问一张图的绘制方法,其本质仍然是误差线图&箱线图的组合,下面小编使用R内置的「gapminder」数据集来简单做一下图形的绘制❞

加载R包

代码语言:javascript
复制
library(tidyverse)
library(gapminder)
library(ggsci)
library(patchwork)

导入数据

代码语言:javascript
复制
df <- gapminder %>% select(continent,year,lifeExp) %>% 
  filter(continent==c("Europe","Oceania","Americas")) %>% 
  mutate(year=as.character(year)) %>% 
  group_by(continent,year) %>% 
  summarise(value_mean=mean(lifeExp),sd=sd(lifeExp),se=sd(lifeExp)/sqrt(n()))

绘制误差线图

代码语言:javascript
复制
p1 <- df %>% ggplot(aes(year,value_mean,fill=continent,group=continent,
                  ymin=value_mean-se,ymax=value_mean+se))+
  geom_errorbar(width=0.1)+
  geom_line(color="black")+
  geom_point(key_glyph="polygon",aes(color=continent))+
  geom_point(pch=21,size=5,show.legend = F)+
  scale_fill_npg()+scale_color_npg()+
  labs(x=NULL,y=NULL)+
  theme_bw()+
  theme(plot.margin=unit(c(0.1,0.1,0.1,0.1),units=,"cm"),
        axis.line = element_line(color = "black",size = 0.4),
        panel.grid.minor = element_blank(),
        panel.grid.major = element_line(size = 0.2,color = "#e5e5e5"),
        axis.text.y = element_text(color="black",size=10),
        axis.text.x = element_text(margin = margin(t=3),color="black",
                                   size=9,angle=90,vjust = 0.5),
        legend.key=element_blank(),
        legend.title = element_blank(),
        legend.text = element_text(color="black",size=8),
        legend.spacing.x=unit(0.1,'cm'),
        legend.spacing.y=unit(1,'cm'),
        legend.key.width=unit(0.7,'cm'),
        legend.key.height=unit(0.4,'cm'),
        legend.background=element_blank(),
        legend.position = c(0.2,0.9),
        legend.box.margin = margin(0,0,0,0))

绘制箱线图

代码语言:javascript
复制
p2 <- df %>% ggplot(aes(continent,value_mean,fill=continent))+
  stat_boxplot(geom="errorbar",width=0.2)+
  geom_boxplot()+
  scale_fill_npg()+scale_color_npg()+
  theme_bw()+
  labs(x=NULL,y=NULL)+
  theme(axis.text = element_text(color="black",angle=90,vjust=0.5,hjust=0.5),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank(),
        legend.position = "non")

拼图

代码语言:javascript
复制
(p1+p2)+plot_layout(widths=c(2,1))

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-06-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 R语言数据分析指南 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 欢迎关注R语言数据分析指南
  • 加载R包
  • 导入数据
  • 绘制误差线图
  • 绘制箱线图
  • 拼图
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档