ggplot2设置坐标轴字体颜色

通过ggplot2的theme()指定坐标轴的每个刻度标签的字体颜色

关键代码

设置X轴:theme(axis.text.x = element_text(colour = Data$Color))
设置Y轴:theme(axis.text.y = element_text(colour = Data$Color))

需求说明

有若干个样本都检出某个物种,需要画检出Reads数的柱状图,当前样本字体颜色和填充颜色为蓝色,其他样本为灰色。

完成示例

坐标轴字体颜色

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
library(ggplot2)

args<-commandArgs(T)
# 数据表
Reads_Table=args[1]
# 输出目录
Result_Dir=args[2]
# 当前样本
Plot_Sample = args[3]

# 读入数据表
Data = read.table(Reads_Table, head=T, sep="\t", comment.char="#", stringsAsFactors=FALSE, check.names=FALSE)

# 设置其他样本和当前样本的分组、颜色信息
List_Color = c("#808080", "#1e90ff")
Data$Group = rep("Other Sample", nrow(Data))
Data$Group[with(Data, Sample==Plot_Sample)] = "This Sample"
Data$Color = rep(List_Color[1], nrow(Data))
Data$Color[with(Data, Sample==Plot_Sample)] = List_Color[2]
if (nrow(Data) == 1){
List_Color = List_Color[2]
}

# 通用主题
plot_font_size=10
if (plot_font_size < 10) {
plot_font_size = 10
}
universal_theme=theme_bw(base_size=plot_font_size)+
theme(axis.line=element_line(size=0.5,colour='black'))+
theme(axis.title.x=element_text(size=plot_font_size-2),axis.title.y=element_text(size=plot_font_size-2))+
theme(axis.text.x=element_text(size=plot_font_size-3,colour='black'),axis.text.y=element_text(size=plot_font_size-3,colour='black'))+
theme(legend.key.size=unit(20,"pt"),legend.title=element_text(size=plot_font_size-2),legend.text=element_text(size=plot_font_size-3))+
theme(panel.border=element_blank())+
theme(plot.title=element_text(hjust=0.5,size=plot_font_size))+
theme(legend.position="none")+
theme(panel.grid=element_blank())

# 画柱状图
picture = ggplot(data=Data, aes(x=Sample, y=Reads, fill=Group)) +
geom_bar(stat="identity", width=0.7) +
labs(x="", y="", title="无乳链球菌") +
scale_y_continuous(expand = c(0,0)) +
scale_fill_manual(values = List_Color) +
universal_theme +
theme(axis.text.y = element_text(colour = rev(Data$Color))) +
coord_flip()

# 保存图片
output_png = paste(Result_Dir, "/", "无乳链球菌.png", sep="", collapse="")
ggsave(output_png, picture, width=8, height=10)

警告信息

使用以上代码画图,会出现警告信息。
这是因为用向量变量在element_text中指定颜色并不是官方支持的标准用法,算是个workaround。
目前是能正常使用的,但在将来的ggplot2版本不一定依然支持这样的用法。

1
2
3
Warning message:
Vectorized input to `element_text()` is not officially supported.
Results may be unexpected or may change in future versions of ggplot2.