library(ggplot2)
bp <- ggplot(PlantGrowth, aes(x=group, y=weight)) +
geom_boxplot()
bp
反轉 x軸 與 y軸bp + coord_flip()離散型數據的坐標軸改變坐標軸中各項目的順序 > 特別注意, 離散數據的坐標軸中數據做為 factor 變量處理,他的位置取決於 level的順序
# 手動設置x軸的位置
bp + scale_x_discrete(limits=c("trt1","trt2","ctrl"))
# 逆轉順序
# 得到 factor 變量的 level
flevels <- levels(PlantGrowth$group)
flevels
## [1] "ctrl" "trt1" "trt2"
# 逆轉了 level 的順序
flevels <- rev(flevels)
flevels
## [1] "trt2" "trt1" "ctrl"
bp + scale_x_discrete(limits=flevels)# 或者寫到一行裡面
bp + scale_x_discrete(limits = rev(levels(PlantGrowth$group)))
scale_x_discrete 可以設置離散型(discrete)數據, 中間的 x 表示處理x軸,如果是 fill 則可以修改填充顏色, color 修改邊框顏色, shape 修改形狀……
設置坐標軸的標籤# 將原有的 "ctrl", "trt1", "trt2" 修改為 "Control", "Treat 1", "Treat 2"
bp + scale_x_discrete(breaks=c("ctrl", "trt1", "trt2"),
labels=c("Control", "Treat 1", "Treat 2"))
# 隱藏
bp + scale_x_discrete(breaks=NULL)
# 也可以這樣通過設置 theme 實現
bp + theme(axis.ticks = element_blank(), axis.text.x = element_blank())
連續型數據的坐標軸設置坐標軸的範圍和顛倒
# Make sure to include 0 in the y axis
bp + expand_limits(y=0) # y軸從0開始
# 設置y軸的範圍
bp + expand_limits(y=c(0,8))
我們可以通過expand_limits設置坐標軸的範圍, 但是如果 scale_y_continuous 被使用, 那麼就會覆蓋ylim的設置.
# 設置y軸的範圍
bp + ylim(0, 8)
# 同樣可以這樣
bp + scale_y_continuous(limits=c(0, 8))
# 如果同時設置 scale_y_continuous 和 ylim那麼ylim會被覆蓋,首先執行scale_y_continuous
bp + scale_y_continuous(limits=c(0, 8))+
ylim(0,10)
## Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
如果 y 的範圍使用上面的方法被截取, 那麼這個範圍以外的數據會被忽略,原始數據中的數據同樣會被忽略,比如設置了ylim(5,8),那麼小於5和大於8的原始數據同樣會被忽略,當然散點圖沒有問題,但是箱線圖會出錯.
為了避免這個問題可以使用coord_cartesian來設置範圍.
可以看下面的例子, 第一個出錯了, 第二個使用了coord_cartesian得到了正確的繪圖.
# These two do the same thing; all data points outside the graphing range are
# dropped, resulting in a misleading box plot
bp + ylim(5, 7.5)
## Warning: Removed 13 rows containing non-finite values (stat_boxplot).
# bp + scale_y_continuous(limits=c(5, 7.5))
# Using coord_cartesian "zooms" into the area
bp + coord_cartesian(ylim=c(5, 7.5))
# Specify tick marks directly
bp + coord_cartesian(ylim=c(5, 7.5)) +
scale_y_continuous(breaks=seq(0, 10, 0.25)) # Ticks from 0-10, every .25
### 點到坐標軸的方向
# Reverse order of a continuous-valued axis
bp + scale_y_reverse()
設置和隱藏坐標軸的刻度# Setting the tick marks on an axis
# 顯示刻度從1到10,間隔為0.25
# The scale will show only the ones that are within range (3.50-6.25 in this case)
bp + scale_y_continuous(breaks=seq(1,10,1/4))
# 未設置刻度的地方會出現空白
bp + scale_y_continuous(breaks=c(4, 4.25, 4.5, 5, 6,8))
# 隱藏刻度
bp + scale_y_continuous(breaks=NULL)
# 隱藏刻度但是顯示標籤
bp + theme(axis.ticks = element_blank())
坐標軸的數據轉換(log, sqrt, etc.)坐標軸可以進行線性變換,比如 log, power, roots 等等
這裡有兩種方式對數據進行轉換, 一種是比例轉換, 另一種是坐標轉換. 對於比例變換, 在坐標軸刻度和範圍被決定之前發生變換, 也就是先繪製圖形,在標明刻度; 對於坐標變換, 在坐標軸刻度和範圍被決定之後發生變換.也就是先標明刻度再繪製圖形.
具體的理解可以看下面的例子.
# 指數分布的數據
set.seed(201)
n <- 100
dat <- data.frame(
xval = (1:n+rnorm(n,sd=5))/20,
yval = 2*2^((1:n+rnorm(n,sd=5))/20)
)
# 散點圖
sp <- ggplot(dat, aes(xval, yval)) + geom_point()
sp
# log2 scaling of the y axis (with visually-equal spacing)
library(scales) # Need the scales package
##
## Attaching package: 'scales'
## The following objects are masked from 'package:readr':
##
## col_factor, col_numeric
# 比例變換 scale transformation
sp + scale_y_continuous(trans=log2_trans())
# 坐標變換
sp + coord_trans(y="log2")
# 設置刻度和標籤
sp + scale_y_continuous(trans = log2_trans(),
breaks = trans_breaks("log2", function(x) 2^x), # 這裡很有意思,可以著重看一下幫助文檔
labels = trans_format("log2", math_format(2^.x)))
這裡還有很多其他的變換, 可以 ?trans_new 查看幫助
set.seed(205)
n <- 100
dat10 <- data.frame(
xval = (1:n+rnorm(n,sd=5))/20,
yval = 10*10^((1:n+rnorm(n,sd=5))/20)
)
sp10 <- ggplot(dat10, aes(xval, yval)) + geom_point()
# log10
sp10 + scale_y_log10()
# 根據 log10 設置 刻度
sp10 + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
labels = trans_format("log10", math_format(10^.x)))
Fixed ratio between x and y axes ### 修改 x 和 y 的比例
# Data where x ranges from 0-10, y ranges from 0-30
set.seed(202)
dat <- data.frame(
xval = runif(40,0,10),
yval = runif(40,0,30)
)
sp <- ggplot(dat, aes(xval, yval)) + geom_point()
# 設置為x:y = 1:1
sp + coord_fixed()
# x:y = 1:3
sp + coord_fixed(ratio=1/3)
坐標軸標籤的格式設置和隱藏坐標標題
bp + theme(axis.title.x = element_blank()) + # Remove x-axis label
ylab("Weight (Kg)") # Set y-axis label
# 另一種方法
bp + scale_x_discrete(name="") +
scale_y_continuous(name="Weight (Kg)")
改變字體和旋轉 刻度標籤element_text 可以設置文本的格式
# Change font options:
# X-axis label: bold, red, and 20 points
# X-axis tick marks: rotate 90 degrees CCW, move to the left a bit (using vjust,
# since the labels are rotated), and 16 points
bp + theme(axis.title.x = element_text(face="bold", colour="#990000", size=20),
axis.text.x = element_text(angle=90,# 設置旋轉的角度
vjust=0.5,# 設置縱向便宜距離 hjust為橫向偏移距離
size=16) # 字體的大小
)
刻度標籤的格式化
# Label formatters
library(scales) # Need the scales package
bp + scale_y_continuous(labels=percent) + # 顯示百分比
scale_x_discrete(labels=abbreviate) #沒有效果
對於連續型數據的格式化包括 comma, percent, dollar 和科學計數法 對於離散型數據的格式化, abbreviate(縮略詞) 將會去除元音和空格,對於日期可以使用 date_format
當然也可以創作自己的格式, 比如 HH:MM:SS 時間格式
# Self-defined formatting function for times.
timeHMS_formatter <- function(x) {
h <- floor(x/60)
m <- floor(x %% 60)
s <- round(60*(x %% 1)) # Round to nearest second
lab <- sprintf('%02d:%02d:%02d', h, m, s) # Format the strings as HH:MM:SS
lab <- gsub('^00:', '', lab) # Remove leading 00: if present
lab <- gsub('^0', '', lab) # Remove leading 0 if present
# 返回 lab
}
bp + scale_y_continuous(label=timeHMS_formatter)
隱藏參考線
# 隱藏所有參考線(minor, major)
bp + theme(panel.grid.minor=element_blank(),
panel.grid.major=element_blank())
# 隱藏 minor
bp + theme(panel.grid.minor=element_blank())
根據坐標軸的方向隱藏
# 隱藏 縱向
bp + theme(panel.grid.minor.x=element_blank(),
panel.grid.major.x=element_blank())
# 隱藏 橫向
bp + theme(panel.grid.minor.y=element_blank(),
panel.grid.major.y=element_blank())