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()
相关推荐
biomooc6 小时前
R 语言 | 绘图的文字格式(绘制上标、下标、斜体、文字标注等)
开发语言·r语言
Tiger Z2 天前
R 语言科研绘图第 6 期 --- 散点图-基础
r语言·贴图
LvManBa2 天前
R 常用的内置软件包及功能介绍
开发语言·r语言·rstudio
新知图书2 天前
R语言的数据结构-数据框
开发语言·r语言
新知图书4 天前
R语言的字符串操作
开发语言·r语言
新知图书4 天前
R语言函数简介
开发语言·python·r语言
还没想好1235 天前
mlr3机器学习AUC的置信区间提取
人工智能·机器学习·r语言·学习笔记
拓端研究室TRL6 天前
R语言混合模型回归GBTM群组轨迹模型绘图可视化研究
开发语言·人工智能·数据挖掘·回归·r语言
_刘文凯_7 天前
R环境配置 以及Debug方法 (VSCode, conda, 远程R)
vscode·r语言·conda
新知图书8 天前
R语言的数据结构-数组
开发语言·数据结构·r语言