在 R 中使用 ggplot2 叠加直方图 [英] Overlaying histograms with ggplot2 in R

查看:92
本文介绍了在 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.

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

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

有人能告诉我用第 1 张图片中的直方图是否可以实现类似的功能?这是我正在使用的代码:

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)

推荐答案

您当前的代码:

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

告诉 ggplot 使用 f0 中的所有值构建 one 直方图,然后根据变量为这个单直方图的条形着色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.

您想要的是创建三个独立的直方图,使用 alpha 混合,以便它们彼此可见.因此,您可能希望对 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天全站免登陆