R语言绘图系列:
- R语言可视化及作图1--基础绘图(par函数,散点图,盒形图,条形图,直方图)
- R语言可视化及作图2--低级绘图函数
- R语言可视化及作图3--图形颜色选取
- R语言可视化及作图4--qplot和ggplot2美学函数
- R语言可视化及作图5--ggplot2基本要素和几何对象汇总
- R语言可视化及作图6--ggplot2之点图、条形图、盒形图、直方图、线图
- R语言可视化及作图7--ggplot2之标签、图例和标题绘制
1. 坐标轴自定义函数
1. 1:标度函数scale
在ggplot2中,坐标轴不是一个几何对象,而必须要由标度函数scale来进行调节。
例1:
library(ggplot2)
p1 <- ggplot(mpg,aes(displ,hwy))+geom_point()
p1

使用scale_x_continous和scale_y_continous定义x轴和y轴标签
p1 + scale_x_continuous('Engine displacement(L)')+scale_y_continuous('Highway MPG')

去掉x轴标签和y轴标签
p1+labs(x=NULL,y=NULL) #xlab和ylab也是用来定义值标签,但是功能较单一。

限制x轴和y轴取值范围
p1+scale_x_continuous(limits = c(0,10))

定义x轴刻度并命名
p1+scale_x_continuous(breaks = c(2,4,6),labels = c('two','four','six'))

例2:
df <- data.frame(x=rnorm(10)*100000,y=seq(0,1,length.out=10))
p2 <- ggplot(df,aes(x,y))+geom_point()
p2

把y轴刻度变成百分数形式
p2+scale_y_continuous(labels = scales::percent)

例3:
针对离散型变量的操作用scale_x_discrere函数
d <- ggplot(subset(diamonds,carat>1),aes(cut,clarity))+geom_jitter()
d

定义刻度
d+scale_x_discrete('Cut',labels=c('Fair'='F','Good'='G','very good'='VG','Premium'='P','Ideal'='I'))

离散型变量limits选取(相当于取子集)
d+scale_x_discrete(limits=c('Fair','Ideal'))

例4:
ggplot(mpg,aes(reorder(manufacturer,displ),cty))+geom_point()+scale_x_discrete(labels=abbreviate)

1. 2:theme函数
设置坐标轴的颜色和线条等
p <- ggplot(mtcars,aes(mpg,wt))+geom_point()
p+theme(axis.title = element_text(color = 'red',size = 18),
#定义坐标轴主题
axis.line = element_line(color = 'blue'),
#定义坐标轴横线
axis.text = element_text(color = 'orange',size = 12),
#定义坐标轴刻度标签
axis.ticks=element_line(color = 'light skyblue',size = 3))

除了标度函数可以自定义坐标轴外,theme()函数也有相应的功能。下表列出了theme()函数中关于坐标轴的一些参数及其用法
参数 | 用法 | 功能 |
---|---|---|
axis.title | 接受函数element_text() | 定义图形坐标轴主题的样式 |
axis.title.x/y | 接受函数element_text() | 分别定义x,y轴的主题样式 |
axis.text | 接受函数element_text() | 定义坐标轴刻度标签样式 |
axis.text.x/y | 接受函数element_text() | 定义x,y轴刻度标签样式 |
axis.ticks | 接受函数element_text() | 定义坐标轴刻度样式 |
axis.ticks.x/y | 接受函数element_text() | 定义x,y轴刻度样式 |
axis.line | 接受函数element_text() | 定义坐标轴横线样式 |
axis.line.x/y | 接受函数element_text() | 定义x,y轴横线样式 |
2. 坐标系转换函数
2.1:极坐标转换函数coord_polar()
library(ggplot2)
a <- ggplot(data=subset(diamonds,color=='E'),aes(factor('E'),fill=cut))+geom_bar()
a #绘制普通的堆叠条图

b <- ggplot(data=subset(diamonds,color=='E'),aes(factor('E'),fill=cut))+geom_bar()+
coord_polar()
b #使用 coord_polar()进行极坐标转换

c <- ggplot(data=subset(diamonds,color=='E'),aes(factor('E'),fill=cut))+geom_bar()+
coord_polar(theta = 'y')
c

c+theme(axis.text = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
panel.background = element_blank(),#去图形背景
panel.grid = element_blank()#去图形背景网格线
)

2.2:坐标轴转换函数: coord_flip()
在笛卡尔坐标系上进行flip
dsmall <- diamonds[sample(1:nrow(diamonds),1000),]
a <- ggplot(dsmall,aes(color,price))+geom_boxplot(fill='darkgreen')+
coord_flip()
a

dsmall <- diamonds[sample(1:nrow(diamonds),1000),]
a <- ggplot(dsmall,aes(color,price))+geom_boxplot(fill='darkgreen')+
coord_flip()
a

网友评论