0. 说明:
1. 绘制条形图;
2. 添加文本并调整位置;
3. 调整x轴刻度的字体、角度及颜色;
4. 在导出pdf时,如果没有字体,该怎么解决问题;
1. 结果:
2. 代码:
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()