用R中的ggplot2覆盖直方图 [英] Overlaying histograms with ggplot2 in R

查看:150
本文介绍了用R中的ggplot2覆盖直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R新手,想把3个直方图绘制到同一张图上。
一切工作正常,但我的问题是,你没有看到2直方图重叠 - 他们看起来相当切断:直方图

I am new to R and am trying to plot 3 histograms onto the same graph. Everything worked fine, but my problem is that you don't see where 2 histograms overlap - they look rather cut off: Histogram

当我制作密度图时,它看起来很完美:每条曲线都被黑色边框线包围,不同的地方曲线重叠:密度图

When I make density plots, it looks perfect: each curve is surrounded by a black frame line, and colours look different where curves overlap: Density Plot

有人可以告诉我,如果第一张照片中的直方图可以达到类似的效果吗?这是我正在使用的代码:

Can someone tell me if something similar can be achieved with the histograms in the 1st picture? This is the code I'm using:

lowf0 <-read.csv (....)
mediumf0 <-read.csv (....)
highf0 <-read.csv(....)
lowf0$utt<-'low f0'
mediumf0$utt<-'medium f0'
highf0$utt<-'high f0'
histogram<-rbind(lowf0,mediumf0,highf0)
ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)

感谢您提供任何有用的提示!

Thanks in advance for any useful tips!

推荐答案

您当前的代码:

Your current code:

ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)

code> ggplot 使用 f0 中的所有值构造一个直方图,然后为此单个直方图根据变量 utt

is telling ggplot to construct one histogram using all the values in f0 and then color the bars of this single histogram according to the variable utt.

您想要的是创建三个单独的直方图,以便它们通过彼此可见。因此,您可能希望对 geom_histogram 使用三个独立调用,其中每个调用都获取它自己的数据框并填充:

What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram, where each one gets it's own data frame and fill:

ggplot(histogram, aes(f0)) + 
    geom_histogram(data = lowf0, fill = "red", alpha = 0.2) + 
    geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
    geom_histogram(data = highf0, fill = "green", alpha = 0.2) +

下面是一些输出的具体例子:

Here's a concrete example with some output:

dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))

ggplot(dat,aes(x=xx)) + 
    geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)

产生如下所示:

编辑修正错别字;你想填充,而不是颜色。

Edited to fix typos; you wanted fill, not colour.

这篇关于用R中的ggplot2覆盖直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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