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()
相关推荐
生信摆渡21 小时前
R语言-快速对多个变量取交集
开发语言·数据库·r语言
biomooc1 天前
R语言/Rstudio 报错
开发语言·r语言
Hello World and You1 天前
R ggplot2 绘图细节 geom_text展示不全 y轴坐标细节 x轴标题
开发语言·r语言
NiNg_1_2343 天前
R语言基础入门详解
开发语言·r语言
rock——you3 天前
R环境依赖的备份与恢复全攻略
开发语言·r语言
biomooc3 天前
R语言 | 宽数据变成一列,保留对应的行名和列名
开发语言·r语言
生信学习小达人3 天前
R package安装的几种方式
开发语言·r语言
卡卡_R-Python4 天前
训练误差or测试误差与特征个数之间的关系--基于R语言实现
开发语言·回归·r语言
亚图跨际5 天前
MATLAB和Python及R瑞利散射
python·matlab·r语言·光学·瑞利散射
不是伍壹5 天前
【R语言】字符类型转换
开发语言·r语言