前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >跟着Eu J Forest Res学作图:R语言ggplot2做柱形图的时候给纵坐标轴添加分组间隔

跟着Eu J Forest Res学作图:R语言ggplot2做柱形图的时候给纵坐标轴添加分组间隔

作者头像
用户7010445
发布2021-11-16 15:36:33
1K0
发布2021-11-16 15:36:33
举报
文章被收录于专栏:小明的数据分析笔记本

今天的推文是回答B站关注者的一个问题

他的问题是

image.png

我找到论文来看了一下

image.png

图片是

image.png

今天的推文我们试着来复现一下这个图

首先是准备数据

没有找到论文提供的原始数据,只能手动将其整理到表格里了。

image.png

这里用qq里面的截图工具识别图片文字还挺方便的

完整代码

代码语言:javascript
复制
library(readxl)
library(ggplot2)

df<-read_excel("abcd.xlsx")
df
df$y<-factor(df$y,
             levels = rev(unique(df$y)))

df$group<-factor(df$group,
                 levels = rev(unique(df$group)))

ggplot(data=df,aes(x=x,y=y,fill=group))+
  geom_bar(stat = "identity",
           position = position_dodge(0.9),
           width = 0.8)+
  scale_fill_manual(values = c("#4472c4","#ed7d31"))+
  geom_text(aes(x+0.2,y,label=x),size=3,
            position = position_dodge(0.9))+
  theme_void()+
  theme(legend.position = "bottom",
        legend.justification = c(0.5,0),
        legend.title = element_blank(),
        legend.key.size = unit(2,'mm'),
        legend.text = element_text(size=10),
        plot.margin = unit(c(1,1,2,1),'mm'))+
  geom_text(aes(x=-0.1,y=y,label=y),hjust=1)+
  xlim(-11,5)+
  geom_vline(xintercept = 0,color="grey")+
  annotate(geom = "segment",
           x=0,xend=-11,y=0.4,yend=0.4,
           color="grey")+
  annotate(geom = "segment",
           x=0,xend=-11,y=2.5,yend=2.5,
           color="grey")+
  annotate(geom = "segment",
           x=0,xend=-11,y=5.5,yend=5.5,
           color="grey")+
  annotate(geom = "segment",
           x=0,xend=-11,y=12.5,yend=12.5,
           color="grey")+
  annotate(geom = "segment",
           x=0,xend=-11,y=16.5,yend=16.5,
           color="grey")+
  annotate(geom = "text",
           x=-11,y=1.5,label="Others",angle=90)+
  annotate(geom = "text",
           x=-11,y=4,label="Provisioning",angle=90)+
  annotate(geom = "text",
           x=-11,y=9,label="Cultural",angle=90)+
  annotate(geom = "text",
           x=-11,y=14.5,label="Regulationg",angle=90) -> p
pdf(file = "outp.pdf",
    width = 14,height = 6,
    family = "serif")
print(p)
dev.off()

image.png

整体的思路就是Y轴的坐标轴标签去掉,用geom_text()函数添加文本注释的办法作为标签,这样有了坐标位置添加横线表示分组就很方便了

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

本文分享自 小明的数据分析笔记本 微信公众号,前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 今天的推文是回答B站关注者的一个问题
  • 我找到论文来看了一下
  • 首先是准备数据
  • 完整代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档