ggplot2坐标轴标尺系统详解

三种常见的坐标轴变换

三种分别为scale_x_log10()、scale_x_sqrt()、scale_x_reverse

library(ggplot2)
set.seed(2018)
mydata1 <- data.frame(
  x = 1:100,
  y = rnorm(100,1000,500)
)
p1 <- ggplot(mydata1, aes(x, y)) + geom_point() ##常规作图
p4 <- p1 + scale_x_log10() + ggtitle("log10")
##等同于 p1 + scale_x_continuous(trans = "log10")
p2 <- p1 + scale_x_sqrt() + ggtitle("sqrt")
##等同于 p1 + scale_x_continuous(trans = "sqrt")
p3 <- p1 + scale_x_reverse() + ggtitle("reverse")
##等同于 p1 + scale_x_continuous(trans = "reverse")
library(cowplot)
## 
## Attaching package: 'cowplot'
## The following object is masked from 'package:ggplot2':
## 
##     ggsave
plot_grid(p1,p2,p3,p4, ncol = 2)

连续性坐标轴参数详解

  • 坐标轴设置的模式 scale_x_continuous(name = waiver(), breaks = waiver(), minor_breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, trans = “identity”, position = “bottom”, sec.axis = waiver())
###修改坐标轴命名
p2 <- p1 + scale_x_continuous(name = "X轴") ##该设置等于 labs(x = "X轴")
p3 <- p1 + scale_x_continuous(limits = c(0,1000)) ###修改坐标轴范围
p4 <- p1 + scale_x_continuous(breaks = seq(25,75,5)) ##修改坐标轴间隔。
p5 <- p1 + scale_x_continuous(minor_breaks = seq(25,75,2.5)) ##修改次级坐标轴间隔
p6 <- p1 + scale_x_continuous(breaks = seq(25,75,5),labels = c(paste0(seq(25,75,5),'个')))##坐标轴的label修改要和主间隔是一样的
p7 <- p1 + scale_x_continuous(expand = c(0,0))#坐标轴刻度线起始位置与绘图区间隔距离,默认情况下连续型:c(0.05,0)
p8 <- p1 + scale_x_continuous(position = "top") ##坐标轴的位置
p9 <- p1 + scale_x_continuous(trans = "log2")
##坐标轴转换包含的参数有"asn", "atanh", "boxcox", "exp", "identity", "log", "log10", "log1p", "log2", "logit", "probability", "probit", "reciprocal", "reverse" and "sqrt".  ##详情见scale包
##设置两个坐标轴
p10 <- p1 + scale_y_continuous(sec.axis = sec_axis(~.+10))
library(cowplot)
plot_grid(p2,p3,p4,p5,p6,p7,p8,p9,p10, ncol = 3, nrow = 3)

离散型坐标轴设置

调整设置类似。

mydata2 <- data.frame(
  x = sample(LETTERS[1:5],20,replace = TRUE),
  y = runif(20,100,500)
)


p1 <- ggplot(mydata2, aes(x, y)) + geom_bar(stat = "identity")

p2 <- p1 + scale_x_discrete(
  name = "X轴",                       #坐标轴轴标题(与labs函数中的x='',y=''标题函数一致,仅需设置一个即可)
  limits = c("A","B","C","D"),        
  breaks = c("C","D"),                #刻度线间隔点
  labels = paste0(c("C","D"),'箱'),   #坐标轴刻度标签
  expand = c(0,0),                    #坐标轴刻度线起始位置与绘图区间隔距离,默认情况下连续型:c(0.05,0)离散型坐标轴:c(0, 0.6)
  position = "top"
)
plot_grid(p1, p2, ncol = 2)
## Warning: Removed 1 rows containing missing values (position_stack).