“ ggplot2中的次级坐标轴
” 生活科学哥-R语言科学 2020-06-12 8:35 在平时作图中,我们有时希望在一个坐标中进行二个坐标轴的设定,也是为了方便数据的显示。这个过程在EXCEL等当中比较容易实现,但是,如何在R中实现呢?今天我们就来讲一讲操作的过程。
数据准备
先准备如下数据:
library(ggplot2)library(scales)library(magrittr)dfdata.frame(x=pdata=df,aes(x=x,y=y))p+geom_bar(stat = "identity")+geom_line()
这是一个最简单的情况,现在,如果我们右边的数据,表示的是原来的数据,经过了除了100的变换(对应%),那么,该如何添加坐标轴呢?其实只需要在scale_y_continous()中添加一个sec_axis的函数,然后进行设定即可。
p1stat = scale_y_continuous(sec.axis = sec_axis(~(./100),name="Percentage(%)",breaks = c(0.025,0.05,0.075,0.1),labels = label_percent())) p1
为了使整个新加的坐标有区分,可以结合theme来调节一些参数,比如颜色
p1<-p+geom_bar(stat = "identity")+geom_line(color="red")+ scale_y_continuous(sec.axis = sec_axis(~(./100),name="Percentage(%)",breaks = c(0.025,0.05,0.075,0.1),labels = label_percent()))p1+theme(axis.title.y.right = element_text(color="red"),axis.line.y.right = element_line(color="red"),axis.text.y.right = element_text(color="red"))