如何使用ggplot2用不同数量的元素覆盖geom_bar和geom_line图? [英] How to overlay geom_bar and geom_line plots with different number of elements using ggplot2?

查看:331
本文介绍了如何使用ggplot2用不同数量的元素覆盖geom_bar和geom_line图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个data.frame,它们的数据不同,但是x值的范围相同

Assuming I have two data.frames with different data but in the same range of x-values

a <-data.frame(x=c(1,1,1,2,2,2,3,3,3),
               y=c(0.3,0.4,0.3,0.2,0.5,0.3,0.4,0.4,0.2), 
               z=c("do","re","mi","do","re","mi","do","re","mi"))

b <- data.frame(x=c(1,2,3),y=c(10,15,8))

a和b都具有相同的X值范围(1,2,3),但是a是具有9行的data.frame,b是具有3行的data.frame.

Both, a and b have the same range of X values (1,2,3) but while a is a data.frame with 9 rows, b is a data.frame with 3 rows.

我使用geom_bar来绘制a的值分布,如下所示:

I use geom_bar in order to plot the distribution of values of a, like this:

ggplot(a, aes(x=x, y=y, fill=z)) +
    geom_bar(position="stack",stat="identity") + 
    ylab("") + 
    xlab("x")

然后我使用geom_line绘制b数据,如下所示:

And I use geom_line to plot b data, like this:

ggplot(b, aes(x=x, y=y)) + 
    geom_line(stat="identity") + 
    ylab("") + xlab("x") + ylim(0,15)

现在,我想将此geom_line图覆盖到先前的geom_bar图上.我的第一次尝试是执行以下操作:

Now I would like to overlay this geom_line plot to the previous geom_bar plot. My first try was to do the following:

ggplot(a, aes(x=x, y=y, fill=z)) +
    geom_bar(position="stack",stat="identity") + 
    ylab("") + xlab("x") +
    ggplot(b, aes(x=x, y=y)) + 
    geom_line(stat="identity") + 
    ylab("") + xlab("x") + ylim(0,15)

没有成功.

如何将geom_line图叠加到geom_bar图上?

How can I overlay a geom_line plot to a geom_bar plot?

推荐答案

尝试一下

p <- ggplot() 
p <- p + geom_bar(data = a, aes(x=x, y=y, fill=z), position="stack",stat="identity")
p <- p + geom_line(data = b, aes(x=x, y=y/max(y)), stat="identity") 
p

更新: 您可以重新缩放一个y以使它们相同.由于我不知道这两个y之间的关系,因此我使用y/max(y)重新调整了它们的比例.这样可以解决您的问题吗?

Update: You can rescale the one y to make them the same. As I don't know the relations between the two ys, I rescaled them by using y/max(y). Does this solve you problem?

这篇关于如何使用ggplot2用不同数量的元素覆盖geom_bar和geom_line图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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