R- split histogram according to factor level

后端 未结 2 1510
野趣味
野趣味 2020-12-02 21:00

This is my data:

type<-rep(c(0,1),100) 
diff<-rnorm(100)
data<-data.frame(type,diff)

If I want to plot historgram of diff

2条回答
  •  被撕碎了的回忆
    2020-12-02 21:38

    That plot was made using the lattice package

    set.seed(1)
    type<-rep(c(0,1),100) 
    diff<-rnorm(100)
    data<-data.frame(type,diff)
    
    
    library('lattice')
    histogram(~ diff | type, data = data)
    

    here is how you can do it in base graphics

    ## first plot - left half of x-axis, right margin set to 0 lines
    par(fig = c(0, .5, 0, 1), mar = c(5,4,3,0))
    hist(data$diff[data$type==0], ann = FALSE, las = 1)
    
    ## second plot - right half of x-axis, left margin set to 0 lines
    par(fig = c(.5, 1, 0, 1), mar = c(5,0,3,2), new = TRUE)
    hist(data$diff[data$type==1], ann = FALSE, axes = FALSE)
    axis(1)
    axis(2, lwd.ticks = 0, labels = FALSE)
    
    title(main = 'Histogram', xlab = 'x label', outer = TRUE, line = -2)
    

提交回复
热议问题