-
火狐截图_2020-02-11T08-36-22.554Z.png
Main title, axis labels and legend title
ggplot2 :主要标题,轴和图例标题
本教程的目的是描述如何使用R软件和ggplot2包修改绘图标题(主标题,轴标签和图例标题)。
可以使用以下函数:
ggtitle(label) # 主标题
xlab(label) # x轴标签
ylab(label) # y轴标签
labs(...) # 主标题、轴标签和图例
(一):数据准备
rm(list = ls())
#convert dose column from a numeric to a factor variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth)
len supp dose
1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10.0 VC 0.5
(二):更改主标题和轴标签
library(ggplot2)
# the axis labs are the variable names as default
p1 <- ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_boxplot()
# change the main title and axis labels
p2 <- p1 + ggtitle("Plot of length \n by dose") +
xlab("Dose(mg)") + ylab("Teeth length")
# Alternatively, change plot title using the function labs() as follow:
p3 <- p1 + labs(title = "Plot of length \n by dose",
x = "Dose(mg)", y = "Teeth length")
library(ggpubr)
ggarrange(p1, p2,p3,
labels = c("A","B","C"),nrow = 1)

- 更改图例标签
# It is also possible to change legend titles using the function labs():
p4 <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose))+
geom_boxplot()
# change legend titles using the function labs():
p5 <- p4 + labs(fill = "Dose (mg)")
ggarrange(p4, p5,
labels = c("A","B"),nrow = 1)
-
Rplot02.png
(三):更改主标题和轴标签的外观
#Change the appearance of the main title and axis labels Default plot
p6 <- ggplot(ToothGrowth, aes(x=dose, y=len,fill = dose)) +
geom_boxplot() +
ggtitle("Plot of length \n by dose") +
xlab("Dose (mg)") + ylab("Teeth length")
# Change the color, the size and the face of the main title, x and y axis labels
p7 <- p6 + theme(
plot.title = element_text(color="red", size=14, face="bold.italic"),
axis.title.x = element_text(color="blue", size=14, face="bold"),
axis.title.y = element_text(color="#993333", size=14, face="bold")
)
ggarrange(p6, p7,
labels = c("A","B"),nrow = 1)

使用ggtitle、xlab、ylab或labs()修改了文本内容;
使用theme修改文本内容外观,如颜色、大小和x/y轴标签;
如果需要隐藏标题和轴,可以使用 element_blank()
附录: element_text() 参数
family : font family
face : font face. Possible values are “plain”, “italic”, “bold” and “bold.italic”
colour : text color
size : text size in pts
hjust : horizontal justification (in [0, 1])
vjust : vertical justification (in [0, 1])
lineheight : line height. In multi-line text,
the lineheight argument is used to change the spacing between lines.
color : an alias for colour
网友评论