Add second x axis to ggplot2

In the “graphic” package, you can add a second x axis (indicating the percentiles of the distribution) to the histogram as follows:

x  <- rnorm(1000)
hist(x, main="", xlab="Bias")
perc  <- quantile(x, seq(from=.00, to=1, by=.1))
axis(1,at=perc,labels=c("0","10%","20%","30%","40%","50%","60%","70%","80%","90%","100%"),cex=0.5, pos= -90)

It looks uncomfortable, of course. So, how can I change the following ggplot2 code to add a second x axis by inverting the percentiles, while the first x axis should indicate the original values ​​?:

library(ggplot2)
theme_classic(base_size = 12, base_family = "")
x  <- rnorm(1000)
qplot(x, main="", xlab="Bias")
perc  <- quantile(x, seq(from=.00, to=1, by=.1))

Any help? Thank you very much in advance!

+4
source share
2 answers

I'm not quite sure what you need, since your first example does not actually create what you are describing.

x , , :

dat <- data.frame(x = rnorm(1000))
perc <- quantile(dat$x,seq(from = 0,to = 1,by = 0.1))
l <- paste(round(perc,1),names(perc),sep = "\n")
> ggplot(dat,aes(x = x)) + 
     geom_histogram() + 
     scale_x_continuous(breaks = perc,labels = l)

enter image description here

+8

, annotate(...) , .

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)

x , annotate(...). . .

@Henrik .

+7

Source: https://habr.com/ru/post/1530860/


All Articles