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()
相关推荐
zhangfeng113318 小时前
BiocManager下载失败 R语言 解决办法
开发语言·r语言
Tiger Z3 天前
《R for Data Science (2e)》免费中文翻译 (第7章) --- Data import(1)
r语言·数据科学·中文翻译
魔力之心4 天前
R notes[2]
开发语言·r语言
Tiger Z5 天前
R 语言科研绘图第 71 期 --- 散点图-边际
r语言·论文·科研·绘图·研究生
小丑尽欢5 天前
R语言根据经纬度获得对应样本的省份
开发语言·r语言
czhc11400756638 天前
Linux 830 shell:expect,ss -ant ,while IFS=read -r line,
linux·运维·r语言
Morpheon8 天前
Intro to R Programming - Lesson 4 (Graphs)
开发语言·r语言
医工交叉实验工坊10 天前
R 语言 ComplexUpset 包实战:替代 Venn 图的高级集合可视化方案
算法·r语言
青春不败 177-3266-052010 天前
R语言贝叶斯方法在生态环境领域中的高阶技术应用
r语言·贝叶斯·生态学·科研绘图·结构方程·环境科学·混合效应
love530love11 天前
怎么更新 cargo.exe ?(Rust 工具链)
人工智能·windows·python·rust·r语言