Representing in one chart two plots in different axes using ggplot

后端 未结 2 1181
情歌与酒
情歌与酒 2021-01-26 21:58

Let\'s reproduce the example we are working with:

chol <- read.table(url(\"http://assets.datacamp.com/blog_assets/chol.txt\"), header = TRUE)
<
相关标签:
2条回答
  • 2021-01-26 22:24

    You can try following. Although I'm not understanding the sense of such overplotting.

    plot1 <- ggplot(data=chol, aes(AGE)) + 
      geom_histogram(breaks=seq(20, 50, by = 2), 
                     col="red", 
                     fill="green", 
                     alpha = .2) + 
      labs(x="Age", y="Count") + 
      xlim(c(18,52)) + 
      ylim(c(0,100))
    
    plot2 <- ggplot(data=chol, aes(WEIGHT)) + 
      geom_histogram() + 
      labs(x="Weigth", y="Count") +
      scale_x_continuous(position = "top")+
      scale_y_reverse(position = "right",limits = c(50,0)) +
      coord_flip()
    
    library(cowplot)
    ggdraw(plot1) + 
      draw_plot(plot2)
    

    0 讨论(0)
  • 2021-01-26 22:33

    I use the code of next blog and I adapted to your example. You have both histograms in one chart, and also a scatterplot.But instead to be infront off they are back to back.

    http://sas-and-r.blogspot.com/2011/06/example-841-scatterplot-with-marginal.html

    scatterhist = function(x, y, xlab="", ylab=""){
    zones=matrix(c(2,0,1,3), ncol=2, byrow=TRUE)
    layout(zones, widths=c(4/5,1/5), heights=c(1/5,4/5))
    xhist = hist(x, plot=FALSE)
    yhist = hist(y, plot=FALSE)
    top = max(c(xhist$counts, yhist$counts))
    par(mar=c(3,3,1,1))
    plot(x,y)
    par(mar=c(0,3,1,1))
    barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0)
    par(mar=c(3,0,1,1))
    barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE)
    par(oma=c(3,3,0,0))
    mtext(xlab, side=1, line=1, outer=TRUE, adj=0, 
          at=.8 * (mean(x) - min(x))/(max(x)-min(x)))
    mtext(ylab, side=2, line=1, outer=TRUE, adj=0, 
          at=(.8 * (mean(y) - min(y))/(max(y) - min(y))))
    }
    
    #with your code#
    
    with(chol, scatterhist(chol$AGE, chol$WEIGHT, xlab="AGE", ylab="WEIHGT"))
    
    0 讨论(0)
提交回复
热议问题