【问题标题】:Display two parallel axes on a ggplot (R)在 ggplot (R) 上显示两个平行轴
【发布时间】:2013-08-29 11:28:35
【问题描述】:

假设我们有以下类型的简单情节。

library(ggplot2)
df = data.frame(y=c(0,1.1,2.3,3.1,2.9,5.8,6,7.4,8.2,9.1),x=seq(1,100, length.out=10))
ggplot(df,aes(x=x,y=y)) + geom_point()

xz 完全相关。关系为:Constant=x^2*z=1.23 因此我可以像这样重写data.frame:

df = cbind(df,1.23/df$x^2)

问题是:

如何在 x 轴上显示两个变量 xz 它可以是一个在底部,一个在顶部,或者两者都在底部。

【问题讨论】:

  • 在 ggplot2 中是不可能的。它可以被网格破解,但每次这样做,哈德利都会杀死一只骆驼。
  • 如果您想要辅助轴,请不要使用ggplot2。使用基本图形(或可能是晶格)要容易得多。
  • 如果有人在这么长时间后来到这里:ggplot2 现在支持 ggplot2.tidyverse.org/reference/sec_axis.html 该文档仅显示了一个次要的 y 示例,但它也适用于 scale_x_continuous

标签: r plot ggplot2 axis-labels


【解决方案1】:

这是一次危险的尝试。具有对数刻度的先前版本只是错误

library(ggplot2)
df = data.frame(y=c(0,1.1,2.3,3.1,2.9,5.8,6,7.4,8.2,9.1),
                x=seq(1,100, length.out=10))
df$z = 1.23/df$x^2


## let's at least remove the gridlines
p1 <- ggplot(df,aes(x=x,y=y)) + geom_point() +
  scale_x_continuous(expand=c(0,0)) +
  theme(panel.grid.major=element_blank(),
        panel.grid.minor = element_blank())

## make sure both plots have expand = c(0,0) 
## otherwise data and top-axis won't necessarily be aligned...
p2 <- ggplot(df,aes(x=z,y=y)) + geom_point() +
  scale_x_continuous(expand=c(0,0))

library(gtable)
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
tmp <- gtable_filter(g2, pattern="axis-b")

## ugly tricks to extract and reshape the axis
axis <- tmp[["grobs"]][[1]][["children"]][["axis"]] # corrupt the children
axis$layout <- axis$layout[2:1,]
axis$grobs[[1]][["y"]] <- axis$grobs[[1]][["y"]] - unit(1,"npc") + unit(0.15,"cm")
## back to "normality"    

g1 <- gtable_add_rows(g1, sum(tmp$heights), 2)
gtableAddGrobs <- gtable_add_grob # alias, making sure @!hadley doesn't see this
g1 <- gtableAddGrobs(g1, 
                     grobs=list(gtable_filter(g2, pattern="xlab"),axis), 
                     t=c(1,3), l=4)
grid.newpage()
grid.draw(g1)

【讨论】:

    【解决方案2】:

    使用出色的 cowplot 库可以实现两全其美的方法。

    library(ggplot2)
    library(cowplot)
    
    data <- data.frame(temp_c=runif(100, min=-5, max=30), outcome=runif(100))
    
    plot <- ggplot(data) + 
      geom_point(aes(x=temp_c, y=outcome)) + 
      theme_classic() + 
      labs(x='Temperature (Celsius)')
    
    x2plot <- ggplot(data) + 
      geom_point(aes(x=temp_c, y=outcome)) + 
      theme_classic() + 
      scale_x_continuous(label=function(x){round(x*(9/5) + 32)}) + 
      labs(x='Temperature (Fahrenehit)')
    
    x <- get_x_axis(x2plot)
    xl <- get_plot_component(x2plot, "xlab-b")
    
    plot_grid(plot, ggdraw(x), ggdraw(xl), align='v', axis='rl', ncol=1, 
              rel_heights=c(0.8, 0.05, 0.05))
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2014-01-26
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 2014-12-30
      • 2019-04-02
      • 1970-01-01
      相关资源
      最近更新 更多