Add second x-axis in ggplot2

后端 未结 2 672
一生所求
一生所求 2021-02-09 04:18

In the \"graphics\" package one can add a second x-axis (indicating the percentiles of the distribution) to a histogram as follows:

x  <- rnorm(1000)
hist(x,          


        
2条回答
  •  失恋的感觉
    2021-02-09 05:01

    Here's another approach which uses annotate(...) and does not require that the two scales have the same breaks.

    library(ggplot2)
    library(grid)
    
    set.seed(123)
    x     <- rnorm(1000)
    perc  <- quantile(x, seq(from=.00, to=1, by=.1))
    labs  <- gsub("\\%","",names(perc))   # strip "%" from names
    yval  <- hist(x,breaks=30,plot=F)$count
    yrng  <- diff(range(yval))
    g1 <- ggplot() +
      geom_histogram(aes(x=x))+ 
      xlim(range(x))+
      coord_cartesian(ylim=c(0,1.1*max(yval)))+
      labs(x="")+
      annotate(geom = "text", x = perc, y = -0.1*yrng, label = labs, size=4) +
      annotate(geom = "text", x=0, y=-0.16*yrng, label="Bias", size=4.5)+
      theme(plot.margin = unit(c(1, 1, 2, 1), "lines"))
    
    g2 <- ggplot_gtable(ggplot_build(g1))
    g2$layout$clip[g2$layout$name == "panel"] <- "off"
    grid.draw(g2)
    

    This adds the second x-axis and the label using annotate(...). The last three lines of code turn off clipping of the viewport. Otherwise the annotations aren't visible.

    Credit to @Henrik for his answer to this question.

提交回复
热议问题