ggplot2绘图系统——坐标轴调节
scale函数:图形遥控器。坐标轴标度函数:
scale_x_continous
scale_y_continous
scale_x_discrete
scale_y_discrete
1. 连续型变量坐标轴
函数及其参数:
scale_x_continuous(name = , #坐标轴标签
breaks = , #定义刻度
minor_breaks = ,
labels = , #刻度标签
limits = ,
expand = c(0.05,0),
#坐标轴延伸,确保图形元素不覆盖坐标
oob = censor,#识别越过边界的点
na.value = NA_real_,
trans = 'identity', #统计变换
position = 'bottom', #left/right/top
sec.axis = #定义第二坐标轴
)
统计变换参数备选:asn/atanh/boxcox/exp/identity/log/log10/log1p/log2/logit/probability/probit/reciprocal/reverse/sqrt
p1 <- ggplot(mpg,aes(displ,hwy))+geom_point()
a=p1+scale_x_continuous('L')+ #同xlab
scale_y_continuous("H")
b=p1+scale_x_continuous(limits = c(0,10)) #同xlim
c=p1+scale_x_continuous(breaks = c(2,4,6),
labels = c('two','four','six'))
gridExtra::grid.arrange(a,b,c,ncol=3)
刻度标签转化为百分比
调用scales包中的percent函数。
prop <- data.frame(sex=rep(c('Male','Female'),each=5),
age=rep(c('0-14','15-34','35-49','50-64','65+'),2),
prop=c(0.12,0.37,0.23,0.17,0.11,0.09,0.33,0.28,0.21,0.09))
ggplot(prop,aes(x=age,weight=prop,fill=sex))+
geom_bar(position = 'dodge')+
scale_y_continuous(labels = scales::percent)+
ylab('Proportion')
2. 离散型坐标轴
针对离散型变量,在条形图、盒形图中使用较多。
d <- ggplot(subset(diamonds,carat>1),aes(cut,clarity))+
geom_jitter()
#重定义坐标轴标签
a=d+scale_x_discrete('Cut',labels=c('Fair'='F','Good'='G','Very Good'='VG',
'Premium'='P','Ideal'="I"))
#取值范围,这里相当于取子集
b=d+scale_x_discrete(limits=c('Fair','Ideal'))
grid.arrange(a,b,nrow=1)
ggplot(mpg,aes(reorder(manufacturer,displ),cty))+
geom_point()+
scale_x_discrete(labels=abbreviate)
#abbreviate函数缩写x轴标签
3. theme函数调节坐标轴
标度函数和theme调节坐标轴分工稍有不同,前者用于框架搭建,后者用于细节修饰。
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主题函数本身不具备生成功能。即不能生成一个坐标轴标签,只能在现有标签基础上进行修饰。
|
请发表评论