R語言與醫學統計圖形-【19】ggplot2坐標軸調節


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)

image.png

刻度標簽轉化為百分比
調用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')

image.png

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)

image.png

ggplot(mpg,aes(reorder(manufacturer,displ),cty))+
  geom_point()+
  scale_x_discrete(labels=abbreviate)
#abbreviate函數縮寫x軸標簽

image.png

3. theme函數調節坐標軸

標度函數和theme調節坐標軸分工稍有不同,前者用於框架搭建,后者用於細節修飾。

theme修飾坐標軸常用參數:
image.png
應用示例。

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))

image.png

theme主題函數本身不具備生成功能。即不能生成一個坐標軸標簽,只能在現有標簽基礎上進行修飾。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM