R ggplot绘制双纵坐标轴

本文介绍了如何利用R语言中的ggplot2包创建具有双纵坐标轴的图形,详细阐述了每个步骤,包括设置坐标轴比例、调整标签以及整合两个数据集的技巧。

p1 <- ggplot(data = DNA_result, mapping = aes( x= num, y = nd)) + 
  geom_point(colour = "red") + 
  xlab( "样本序号") + 
  ylab("浓度")+
  theme(plot.caption = element_text(hjust = 0))+ theme_bw()
p1

p2 <- ggplot(data = DNA_result, mapping = aes( x= num, y = A280)) + 
  geom_point(colour = "blue") + 
  xlab( "样本序号") + 
  ylab("A260/A280")+
  theme(plot.caption = element_text(hjust = 0))+ theme_bw() %+replace% 
  theme(panel.background = element_rect(fill = NA))
p2

double_y_axis <- function(p1, p2){
  g1 <- ggplot_gtable(ggplot_build(p1))
  g2 <- ggplot_gtable(ggplot_build(p2))
  
  # overlap the panel of 2nd plot on that of 1st plot
  pp <- c(subset(g1$layout, name == "panel", se = t:r))
  g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, pp$l, pp$b, pp$l)
  
  # axis tweaks
  ia <- which(g2$layout$name == "axis-l")
  ga <- g2$grobs[[ia]]
  ax <- ga$children[[2]]
  ax$widths <- rev(ax$widths)
  ax$grobs <- rev(ax$grobs)
  ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
  g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
  g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)
  
  # draw it
  grid.draw(g)
  return(g)
}
double_y_axis(p1,p2)

ref1  

ref2

ref3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值