在一张图中使用ggplot表示不同轴上的两个图 [英] Representing in one chart two plots in different axes using ggplot

查看:158
本文介绍了在一张图中使用ggplot表示不同轴上的两个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's reproduce the example we are working with:

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

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

We are now representing two ggplot histograms:

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和第二个plot2.

These are the two histogramas, first plot1 and second plot2.

我想合并它们,在新图的X轴上表示plot1,在Y轴上表示plot2.结果可能类似于以下内容:

I would like to merge both of them, representing plot1 in the X axis, and plot2 in the Y axis of the new plot. The result might be similar to this:

我如何实现这个目标?

推荐答案

您可以尝试以下方法.尽管我不了解这种过度绘图的感觉.

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)

这篇关于在一张图中使用ggplot表示不同轴上的两个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆