# install.packages('ggplot2') 安装ggplot2包
# install.packages('gcookbook') 安装gcookbook包
library(ggplot2) #加载ggplot2包
library(gcookbook) #加载本书的数据包
改变字体类型、大小,图例、坐标轴、背景等各种元素,可通过theme()函数来完成
library(ggplot2)
library(grid) #为了使用unit函数
p0 <- ggplot(data = mpg, aes(x = displ, fill = factor(cyl))) + geom_bar(colour = 1,
binwidth = 0.2) + labs(title = "plot title")
p0 #基础图
将图片区背景填充色设置为lightblue,边框颜色设置为黑色,宽度设置为3,线型设置为虚线,图标题的字体颜色为黑色,粗体,字体大小30,顶部对齐,同时设置图边沿距离
p0 + theme(plot.background = element_rect(colour = "black", size = 3, linetype = 4,
fill = "lightblue"), plot.title = element_text(colour = "black", face = "bold",
size = 30, vjust = 1), plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "inches"))
p0
p0 + theme(panel.background = element_rect(fill = "lightblue")) #将图片区的背景色设置为lightblue
p0 + theme(panel.background = element_rect(fill = "lightblue", colour = "red",
size = 3)) #将图片区的背景色设置为lightblue,边框颜色为红色,边框宽度为3
p0
axis_theme<-theme(
axis.title=element_text(
#family=NULL,
face = "bold", #字体("plain", "italic", "bold", "bold.italic")
colour = "red", #字体颜色
size = 25,#字体大小
hjust = .5, #调整轴标题1:纵轴靠上,横轴靠右;0.5居中;0:纵轴靠下,横轴靠左
vjust = .5, #1:靠图边框;0靠近轴线;.5居中
angle = 0 #为什么只对横轴标题有作用?
),
axis.title.x=element_text(colour="blue"),#x轴标题设置,优先级高于axis.title
axis.title.y=element_text(colour="orange"),#同上
axis.text=element_text(colour="red"),#设置坐标轴刻度数字
axis.text.x=element_text(colour="blue"),#优先级高于aixis.text
axis.text.y=element_text(colour="orange"),#同上
axis.ticks=element_line(#坐标轴刻度线的设置
colour="red",
size=.5,
linetype=1,
lineend=1),
axis.ticks.x=element_line(colour="blue"),#优先级高于axis.ticks
axis.ticks.y=element_line(colour="orange"),#同上
axis.ticks.length=unit(.4,"lines"),#设置刻度线的高度
axis.ticks.margin=unit(.4,"cm"),#设置刻度数字与刻度线的距离
axis.line=element_line(#设置轴线
colour="red"),
axis.line.x=element_line(colour="blue"),#设置x轴线,优先于axis.line
axis.line.y=element_line(colour="orange"))#类似axis.line.x
p0+axis_theme
p0
legend_theme<-theme(
legend.background=element_rect(
colour=NA,#图例边框颜色
fill="lightblue"),#图例背景填充色
legend.margin=unit(.2,"inches"),#图例与图片区边缘的距离
legend.key=element_rect(fill="yellow"),
legend.key.size=unit(.2,"inches"),#图例分类符号的大小
legend.key.height=unit(.5,"inches"),#图例分类符号高度
legend.key.width=unit(.5,"inches"),#图例符号的宽度
legend.text=element_text(colour="red",size=20),#图例分类标签设置
legend.text.align=0,#0左,1右,0.5居中, 图例分类标签的对齐方式
legend.title=element_text(colour="blue",size=20),#图例标题设置
legend.title.align=1,#图例标题对齐方式
legend.position=c(0.6,.7),#"none","left","right","bottom","top",or
# two-element numeric vector,(0,0)-(1,1)
legend.direction="horizontal",#"vertical" 图例排列方向
legend.justification=c(.4,.4),#"center" or two-element numeric vector
legend.box="vertical",#"horizontal",对图例的排列方式
legend.box.just="top"#多图例的居中方式
)
p0+legend_theme