ggplot2学习之5——图形微调1

说明

R语言的版本为4.0.2,IDE为Rstudio,版本为1.3.959。本次学习的内容是依据一组数据,画出样条曲线拟合图,并输出为高DPI图片。
学习过程中主要参考了以下文章:
R语言绘图高质量输出(博客园)
ggplot2学习笔记系列之利用ggplot2绘制散点图(简书)
使用ggplot2 如何修改刻度方向 ,使刻度朝内?(知乎)
如何在ggplot2里将图片文字改成微软雅黑(CSDN)
ggplot2一页多图(简书)
ggplot2作图详解7(完):主题(theme)设置 (新浪)
R语言之正则表达式(博客园)

1、图形微调效果

在这里插入图片描述 在这里插入图片描述
微调之前 微调之后
## 未经调整 

waveFile <- file('weave.txt')
wave <- scan(file = waveFile)
close(waveFile)
library(ggplot2)
time <- c(1990:2016)[-17][-15]
waveLine <- data.frame(time = time, wave = wave)
sWaveLine <- data.frame(spline(waveLine, n = 6000))
ggplot(waveLine, aes(time, wave)) +
  geom_point(colour="red", shape="*", size=6) +
  geom_line(data=sWaveLine, aes(x=x, y=y), size = 0.3)


## 调整之后 

waveFile <- file('weave.txt')
wave <- scan(file = waveFile)
close(waveFile)
time <- c(1:25)
waveLine <- data.frame(time = time, weave = weave)
sWaveLine <- data.frame(spline(waveLine, n = 6000))
library(ggplot2)
weavePlot <- ggplot(waveLine, aes(time, weave)) +
  geom_point(colour="red", shape=8, size=2) +
  geom_line(data=sWaveLine, aes(x=x, y=y), size = 0.3) +
  theme_bw() + 
  theme(panel.grid = element_blank(),
        axis.line = element_line(size = 0.1),
        axis.ticks.length = unit(-0.2,"cm"),
        axis.title.x=element_text(family="serif",size=17, margin = unit(rep(0.1, 4), 'cm')),
        axis.title.y=element_text(family="serif",size=17, margin = unit(rep(0.1, 4), 'cm')),
        axis.text.x=element_text(family="serif",size=17, margin = unit(rep(0.6, 4), 'cm')),
        axis.text.y=element_text(family="serif",size=17, margin = unit(rep(0.6, 4), 'cm')))+
  ylab("Wave(m)") +
  xlab("Time(year)") +
  scale_x_continuous(breaks = seq(1,27,3),
                     expand = c(0,0),
                     labels =c("1990","1993","1996","1999","2002","2006","2010","2013","2016"),
                     sec.axis = sec_axis(~./0.999,name="", breaks=seq(1,27,3),
                                         labels=c(" "," "," "," "," "," "," "," "," "))) +
  scale_y_continuous(breaks = seq(0,8,2),
                     limits = c(0,8),
                     expand = c(0,0),
                     labels =c("0","2","4","6","8"),
                     sec.axis = sec_axis(~./0.999,name="", breaks=seq(0,8,2),
                                         labels=c(" "," "," "," "," ")))
require(Cairo)
ggsave("wavePlot.pdf", weavePlot, width = 9.36, height = 4.29) 

2、调整坐标轴

调整坐标轴主要有三种方法:

  1. 通过 labs 调整坐标轴标签
  2. 通过 lims 调整刻度范围
  3. 通过 theme 控制具体细节
在这里插入代码片

2.1 labs 调整轴标签

# 该函数有三个快捷方法,分别是
# xlab(label):快捷设置x轴标题
# ylab(label):快捷设置y轴标题
# ggtitle(label, subtitle = waiver()):快捷设置图标题
# 它们是 labs()类的快捷实现,用 labs()也能达到同样的效果
# 例如以下两种写法等价

ylab("Wave(m)") +
xlab("Time(year)")

labs(x="Wave(m)", y="Time(year)")

2.2 lims 调整刻度范围

需注意,用该函数修改刻度范围会与 scale 函数中修改范围重复,最终仅有一个生效

# 该函数有两个快捷方法
# xlim(...):快捷设置x轴刻度范围
# ylim(...):快捷设置y轴刻度范围
# 二者是 lims()函数的快捷实现,用 lims()也能实现
# 例如以下两种写法等价

ylim(0,10)

lims(y=c(0,10))

2.3 theme 调整具体细节

对于坐标轴而言,主要调整 theme 函数中 axis 参数的值

## 该类中axis参数有很多

# axis.title 全局轴标题,以下表示具体轴标题
# axis.title.x
# axis.title.x.top
# axis.title.x.bottom
# axis.title.y
# axis.title.y.left
# axis.title.y.right
# 修改该参数需要借助 element_text(),文字元素生成函数
# 该函数的参数、含义列举如下
# family:字体,需要先引入windows字体,然后使用
#    例如:windowsFonts(A=windowsFont("微软雅黑"))
#          plot(1:10, 1:10, type="n")
#          text(6,4,"微软雅黑", family="A")
# face:字体样式,字符串设置倾斜、加粗等
# colour,color:线条或者边框的颜色,颜色名或RGB名
# size:线条(mm)、边框(mm)、文字(pt)的尺寸
# hjust:水平对齐,值在0-1之间
# vjust:竖向对齐,值在0-1之间
# angle:旋转角度,值在0-360之间
# lineheight:线高度,数值
# margin:文字周围的留白,
# debug:辅助可视化调试,逻辑值
# inherit.blank:是否从父类继承留白,逻辑值

axis.title.x=element_text(family="serif",size=17, margin = unit(rep(0.1, 4), 'cm'))

# axis.text 全局轴刻度标签,以下表示具体轴刻度标签
# axis.text.x
# axis.text.x.top
# axis.text.x.bottom
# axis.text.y
# axis.text.y.left
# axis.text.y.right
# 修改该参数需要借助 element_text(),文字元素生成函数
# 该函数的参数、含义列举如下
# family:字体,需要先引入windows字体,然后使用
#    例如:windowsFonts(A=windowsFont("微软雅黑"))
#          plot(1:10, 1:10, type="n")
#          text(6,4,"微软雅黑", family="A")
# face:字体样式,字符串设置倾斜、加粗等
# colour,color:线条或者边框的颜色,颜色名或RGB名
# size:线条(mm)、边框(mm)、文字(pt)的尺寸
# hjust:水平对齐,值在0-1之间
# vjust:竖向对齐,值在0-1之间
# angle:旋转角度,值在0-360之间
# lineheight:线高度,数值
# margin:文字周围的留白,
# debug:辅助可视化调试,逻辑值
# inherit.blank:是否从父类继承留白,逻辑值

axis.text.x=element_text(family="serif",size=17, margin = unit(rep(0.6, 4), 'cm'))
 
# axis.ticks 全局轴刻度线,以下表示具体轴刻度
# axis.ticks.x
# axis.ticks.x.top
# axis.ticks.x.bottom
# axis.ticks.y
# axis.ticks.y.left
# axis.ticks.y.right 
# 修改参数值还需借助 element_line(),线元素生成函数
# 该函数的参数、含义列举如下
# colour,color:线条或者边框的颜色,颜色名或RGB名
# size:线条(mm)、边框(mm)、文字(pt)的粗细
# linetype:线型,用数字1-8或者字符串指定,
# lineend:线两端的形状,用字符串指定
# arrow:线条末端箭头,要借助 arrow() 函数构造箭头
#    例如:arrow(angle = 30, length = unit(0.25, "inches"),
#               ends = "last", type = "open")
# inherit.blank:是否从父类继承留白,逻辑值

axis.ticks = element_line(size = 0.1)
 
# axis.ticks.length 全局刻度长度,以下表示具体刻度长度
# axis.ticks.length.x
# axis.ticks.length.x.top
# axis.ticks.length.x.bottom
# axis.ticks.length.y
# axis.ticks.length.y.left
# axis.ticks.length.y.right
# 直接给该参数赋值即可,负值代表反方向,使用unit可转换单位

axis.ticks.length = unit(-0.2,"cm")
 
# axis.line 全局轴线,以下表示具体轴线
# axis.line.x
# axis.line.x.top
# axis.line.x.bottom
# axis.line.y
# axis.line.y.left
# axis.line.y.right
# 修改参数值还需借助 element_line()线元素生成函数
# 该函数的参数、含义列举如下
# colour,color:线条或者边框的颜色,颜色名或RGB名
# size: 线条(mm)、边框(mm)、文字(pt)的尺寸
# linetype:线型,用数字1-8或者字符串指定,
# lineend:线两端的形状,用字符串指定
# arrow:线条末端箭头,要借助 arrow() 函数构造箭头
#    例如: arrow(angle = 30, length = unit(0.25, "inches"),
#               ends = "last", type = "open")
# inherit.blank:是否从父类继承留白,逻辑值

axis.line = element_line(size = 0.1)

3、调整背景画布

背景画布的调节主要有两种方式:

  1. 通过快捷主题函数调节
  2. 通过 theme 中的 panel 参数调节

3.1 调节主题函数

在这里插入图片描述
p13:
在这里插入图片描述

# 快捷主题函数有以下几种,是已经设定好的主题模板

library("cowplot")
xx <-  c(1:5)
yy <-  c(1:5)
line <- data.frame(x =xx, y = yy)
plot <- ggplot(line, aes(xx,yy)) + 
  geom_point(colour="red", shape=8, size=2)
p1 <- plot+theme_bw()
p2 <- plot+theme_classic()
p3 <- plot+theme_dark()
p4 <- plot+theme_get()
p5 <- plot+theme_gray()
p6 <- plot+theme_grey()
p7 <- plot+theme_light()
p8 <- plot+theme_linedraw()
p9 <- plot+theme_minimal()
p10 <- plot+theme_replace()
p11 <- plot+theme_test()
p12 <- plot+theme_update()
plot+theme_void()
plot_grid(p1, p2, p3, p4, p5, p6, p7, p8, 
                   p9, p10, p11, p12, p13, nrow = 2, ncol = 6, 
                   labels = c('p1', 'p2', 'p3', 'p4',
                              'p5', 'p6', 'p7', 'p8', 
                              'p9', 'p10', 'p11', 'p12', ))

3.2 theme 调整细节

对于背景而言,主要调整 theme 函数中 panel 参数的值
在这里插入图片描述

# panel.background 画布背景
# 调节该参数,需要依靠element_rect(),边界和背景生成函数
# 该函数的参数、含义列举如下
# fill:填充颜色,颜色名或RGB名
# colour,color:线条或者边框的颜色,颜色名或RGB名
# size:线条(mm)、边框(mm)、文字(pt)的尺寸
# linetype:线型,用数字1-8或者字符串指定,

library("cowplot")
xx <-  c(1:5)
yy <-  c(1:5)
line <- data.frame(x =xx, y = yy)
plot <- ggplot(line, aes(xx,yy)) + 
  geom_point(colour="red", shape=8, size=2)
plot1 <- plot +  theme(panel.background = element_rect(fill = "blue",
                                                       color = "red",
                                                       size = 2,
                                                       linetype = 3))
plot_grid(plot, plot1, nrow = 1, ncol = 2, 
          labels = c('plot', 'plot1'))

# panel.border 边框
# 调节该参数,需要依靠element_rect(),边界和背景生成函数

# panel.spacing # 不同子plot之间距离大小,以下是具体方向
# panel.spacing.x
# panel.spacing.y

# panel.grid 全局栅格线,以下是具体栅格线
# panel.grid.major 
# panel.grid.minor
# panel.grid.major.x
# panel.grid.major.y
# panel.grid.minor.x
# panel.grid.minor.y
# 修改参数值需借助 element_line(),线元素生成函数

# panel.ontop 逻辑值,将背景层和栅格层放到数据层之上

4、调整标尺

标尺的调整使用scale函数进行操作,其中包含的函数有121个之多,但是其逻辑有些混乱,我按照自己的理解梳理以下。

4.1 三种标尺

# 使用正则表达式列出所有标尺函数的个数

library(ggplot2)
scalex <- ls("package:ggplot2", pattern = "^scale.+")
length(scalex)

# 按照命名方式对标尺归类

scalex <- scalex[grep("([^_]+_){2}.+", scalex)]
unique(gsub("(([^_]+_){2}).+", "\\1***", scalex))

# 输出结果为:
 [1] 121
 [1] "scale_alpha_***"      "scale_color_***"     
 [3] "scale_colour_***"     "scale_continuous_***"
 [5] "scale_discrete_***"   "scale_fill_***"      
 [7] "scale_linetype_***"   "scale_shape_***"     
 [9] "scale_size_***"       "scale_x_***"         
 [11] "scale_y_***" 

# 在实际运用中发现如果理解成有11种标尺,发现不恰当
# 按照一张图的要素来讲,实际上只有3种标尺,分别是

# 1、表现在x轴上的标尺,包括
# "scale_x_***" 其具体函数,用于设置在x轴上显示的标尺参数
# 2、表现在y轴上的标尺,包括
# "scale_y_***" 其具体函数,用于设置在y轴上显示的标尺参数
# 3、表现在一侧图例上的标尺,包括
# "scale_alpha_***" 其具体函数,用于设置在x轴
# "scale_color_***" 
# "scale_colour_***" 
# "scale_continuous_***" 
# "scale_discrete_***" 
# "scale_fill_***" 
# "scale_linetype_***" 
# "scale_shape_***" 
# "scale_size_***" 

4.2 x轴上的标尺

在这里插入图片描述

# "scale_x_continuous" 更改默认x轴标尺的属性
# "scale_x_binned" 累计图x轴标尺
# "scale_x_continuous" 默认x轴标尺
# "scale_x_date" 日期格式的x轴标尺
# "scale_x_datetime" 日期格式的x轴标尺
# "scale_x_discrete" 离散的的x轴标尺       
# "scale_x_log10" 对数形式的x轴标尺
# "scale_x_reverse" 颠倒的x轴标尺
# "scale_x_sqrt" 开方形式的x轴标尺
# "scale_x_time" 时间格式的x轴标尺

library("cowplot")
xx <-  c(1:5)
yy <-  c(1:5)
zz <-  c(0,0.5,0.1,0.3,3)
line <- data.frame(x =xx, y = yy)
plot <- ggplot(line, aes(xx,yy)) + 
  geom_point(colour="red", shape=8, size=2)
plot1 <- plot
plot2 <- plot +
  scale_x_continuous(breaks = c(1:5),
                     expand = c(0,0),
                     labels =c("1990","1993","1996","1999","2002"),
                     sec.axis = sec_axis(~./0.999,name="", breaks=c(1:5),
                                         labels=c(" "," "," "," "," ")))
plot_grid(plot1, plot2, nrow = 1, ncol = 2, 
          labels = c('plot1', 'plot2'))

4.3 y轴上的标尺

使用方法和参数与x轴上的完全一致。

4.4 图例上的标尺

4.4.1 透明度标尺

在这里插入图片描述

# "scale_alpha_***" 透明度型标尺,对映射到透明度上的数据起作用

library("cowplot")
xx <-  c(1:5)
yy <-  c(1:5)
zz <-  c(0,5,1,3,3)
line <- data.frame(x =xx, y = yy)
plot <- ggplot(line, aes(xx,yy)) + 
  geom_point(colour="red", shape=8, size=2, aes(alpha = zz))
plot1 <- plot +
  scale_alpha(range = c(0.3, 0.7))
plot_grid(plot, plot1, nrow = 1, ncol = 2, 
          labels = c('plot', 'plot1'))

4.4.2 颜色标尺

在这里插入图片描述

# "scale_color_***" 离散型颜色标尺
# "scale_colour_***" 离散型颜色标尺
# "scale_fill_***" 连续型颜色标尺
# 当数据特别多的时候,更加明显,此时数据较少

library("cowplot")
xx <-  c(1:5)
yy <-  c(1:5)
zz <-  c(0,0.5,0.1,0.3,3)
line <- data.frame(x =xx, y = yy)
plot <- ggplot(line, aes(xx,yy,fill = zz)) + 
  geom_tile()
plot1 <- plot +
  scale_fill_continuous(type = "gradient")
plot2 <- plot +
  scale_color_continuous(type = "gradient")
plot_grid(plot, plot1, nrow = 1, ncol = 2, 
          labels = c('plot1', 'plot2'))

在这里插入图片描述

# 此时数据较多

library("cowplot")
v <- ggplot(faithfuld, aes(waiting, eruptions, fill = density)) +
  geom_tile()
plot1 <- v + scale_color_continuous(type = "gradient")
plot2 <- v + scale_fill_continuous(type = "viridis")

# 以下是上面的快捷函数

v + scale_fill_gradient()
v + scale_fill_viridis_c()
plot_grid(plot1, plot2, nrow = 1, ncol = 2, 
          labels = c('plot1', 'plot2'))

4.4.3 其他标尺

# "scale_linetype_***" 线型标尺
# "scale_shape_***" 形状标尺
# "scale_size_***" 大小标尺

5、输出高DPI图片

# 使用Cairo包输出为PDF形式的矢量图,再用AI打开,导出为高清PNG位图
require(Cairo)
ggsave("wavePlot.pdf", weavePlot, width = 9.36, height = 4.29)
ggplot(data, aes(x = x, y = y)) + geom_line(size = 1) +
  theme_bw()
  
#最后关闭图像设备,同时储存图片
dev.off() 

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42318112/article/details/107075899
今日推荐