使用ggplot在一个图表中表示两个不同轴的图

时间:2018-05-30 11:24:10

标签: r ggplot2

让我们重现我们正在使用的例子:

chol <- read.table(url("http://assets.datacamp.com/blog_assets/chol.txt"), header = TRUE)

我们现在代表两个ggplot直方图:

library(ggplot2)
plot1 <- ggplot(data=chol, aes(chol$AGE)) + 
geom_histogram(breaks=seq(20, 50, by = 2), 
               col="red", 
               fill="green", 
               alpha = .2) + 
labs(title="Histogram for Age") +
labs(x="Age", y="Count") + 
xlim(c(18,52)) + 
ylim(c(0,100))

plot2 <- ggplot(data=chol, aes(WEIGHT)) + 
    geom_histogram() + 
    labs(title="Histogram for Weigth") +
    labs(x="Weigth", y="Count") +
    ylim(0,50)

这是两个直方图,第一个plot1和第二个plot2enter image description here enter image description here

我想合并它们,在X轴上表示plot1,在新图表的Y轴上表示plot2。结果可能与此类似: enter image description here

我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作。虽然我不理解这种过度绘制的感觉。

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)

enter image description here

答案 1 :(得分:0)

我使用下一个博客的代码,我适应了你的例子。你在一个图表中有两个直方图,还有一个散点图。但是它们是在前面,它们背靠背。

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"))