R语言绘图-5-条形图(修改坐标轴以及图例等)

0. 说明:

1. 绘制条形图;
2. 添加文本并调整位置;
3. 调整x轴刻度的字体、角度及颜色;
4. 在导出pdf时,如果没有字体,该怎么解决问题;

1. 结果:

2. 代码:

r 复制代码
library(ggplot2)
library(hrbrthemes)
library(sysfonts) ## 添加字体
library(showtext) ## 显示字体

#font_add("Times New Roman", "/Users/zzy/fonts_R/Times_new_roman_bold.ttf") ## 手动添加字体 (字体名称,字体包路径)
pdf("/Users/zzy/Desktop/linshi.pdf", width = 6, height = 5) # 打开图形设备
showtext_begin() 


dt = data.frame(category = c("A", "B", "C", "D", "E", "F", "G", "H",
                              "I","J","K",
                              "L","M","N","O","P","Q"),
                 value = c(10, -20, 15, 25, 30, 20, -10, 30,
                           20, 5, -50,
                           -10, 10, 3, 3, 2, -5),
                groups = c("pos","pos","pos","neg","neg","pos","neg","pos",
                        "pos","pos","pos",
                        "neg","pos","pos","neg","neg","pos"),
                text = c("*","","","","**","","","***",
                         "","","*",
                         "*","","*","*","",""))

## 指定特定的顺序
dt$category = factor(dt$category, levels = c("D", "E", "F", "G", "H", "A", "B", "C",
                                           "I","J","K",
                                           "N","O","P","Q","L","M"))
## 添加调整位置的列
pos_list = c()
for (v in dt$value){
  if (v>0){
    pos_list = c(pos_list, 0.5)
  }else{
    pos_list = c(pos_list, 1)
  }
}
dt$pos_list = pos_list

## 添加颜色列
dt$diycolor = c(rep("red",8), rep("blue", 3), rep("green", 6))

## 绘图
ggplot(data=dt, aes(x=category, y=value, fill=groups))+
  geom_bar(stat = "identity")+ ## 绘制条形图,stat使用identity,显示原始数据
  geom_text(aes(label=text), color="black", size=8, vjust=dt$pos_list) + ## 添加并调整星号的位置
  scale_fill_manual(values = c("red", "blue"))+
  ylab("Value")+
  theme_classic()+
  theme(axis.text.x = element_text(angle=45, hjust = 1, vjust=1, color=dt$diycolor), ## 调整 x 坐标轴刻度,旋转,并分组赋予颜色
        axis.text = element_text(size=15, face ="bold"),  ## x和y坐标轴刻度字体调整
        axis.title.x = element_blank(), ## 不显示x坐标轴标题
        axis.title.y = element_text(size=15, face="bold"),
        legend.position = "none") ## 不显示图例



showtext_end() 
dev.off()
相关推荐
有梦想的Frank博士18 小时前
R语言*号标识显著性差异判断组间差异是否具有统计意义
开发语言·信息可视化·r语言
逆风远航4 天前
R语言贝叶斯:INLA下的贝叶斯回归、生存分析、随机游走、广义可加模型、极端数据的贝叶斯分析
开发语言·r语言·贝叶斯·生态学·结构方程·环境科学·混合效应
Faxxtty4 天前
【R语言】解决package ‘qvalue’ is not available (for R version 3.6.1)
开发语言·r语言
Cachel wood5 天前
Vue前端框架:Vue前端项目文件目录
java·前端·vue.js·python·算法·r语言·前端框架
邢博士谈科教5 天前
OmicsTools软件和R语言分析环境安装配置答疑汇总最新版
r语言
纪伊路上盛名在6 天前
vscode中提升效率的插件扩展——待更新
linux·服务器·ide·vscode·python·r语言·编辑器
拓端研究室TRL6 天前
银行信贷风控专题:Python、R 语言机器学习数据挖掘应用实例合集:xgboost、决策树、随机森林、贝叶斯等...
python·决策树·机器学习·数据挖掘·r语言
在在进步6 天前
R数据结构&向量基础
数据结构·r语言
琼火hu8 天前
R语言笔记(五):Apply函数
开发语言·笔记·r语言·apply
扛着仪器去爬山8 天前
R语言结构方程模型(SEM)
r语言·贝叶斯·生态学·结构方程·混合效应·sem