如何在具有融化数据的ggplot中缩放密度图(针对多个变量) [英] How to scale density plots (for several variables) in ggplot having melted data
问题描述
我有一个融化的数据集,其中还包括从正态分布生成的数据.我想针对正态分布绘制数据的经验密度函数,但两个生成的密度图的比例不同.我可以在这篇文章中找到两个单独的数据集:
I have a melted data set which also includes data generated from normal distribution. I want to plot empirical density function of my data against normal distribution but the scales of the two produced density plots are different. I could find this post for two separate data sets:
但是我不知道如何将其应用于合并的数据.假设我有一个像这样的数据框:
but I couldn't figure out how to apply it to melted data. Suppose I have a data frame like this:
df<-data.frame(type=rep(c('A','B'),each=100),x=rnorm(200,1,2)/10,y=rnorm(200))
df.m<-melt(df)
使用以下代码:
qplot(value,data=df.m,col=variable,geom='density',facets=~type)
产生此图:
鉴于正态分布是参考图,我如何使两个密度具有可比性? (我更喜欢使用qplot
而不是ggplot
)
How can I make the two densities comparable given the fact that normal distribution is the reference plot? (I prefer to use qplot
instead of ggplot
)
更新:
我想生成类似这样的内容(例如,在情节比较方面),但要使用ggplot2
:
UPDATE:
I want to produce something like this (i.e. in terms of plot-comparison) but with ggplot2
:
plot(density(rnorm(200,1,2)/10),col='red',main=NA) #my data
par(new=T)
plot(density(rnorm(200)),axes=F,main=NA,xlab=NA,ylab=NA) # reference data
生成以下内容:
推荐答案
df<-data.frame(type=rep(c('A','B'),each=100),x = rnorm(200,1,2)/10, y = rnorm(200))
df.m<-melt(df)
require(data.table)
DT <- data.table(df.m)
将具有缩放值的新列插入DT.然后绘图.
Insert a new column with the scaled value into DT. Then plot.
这是图像代码:
DT <- DT[, scaled := scale(value), by = "variable"]
str(DT)
ggplot(DT) +
geom_density(aes(x = scaled, color = variable)) +
facet_grid(. ~ type)
qplot(data = DT, x = scaled, color = variable,
facets = ~ type, geom = "density")
# Using fill (inside aes) and alpha outside(so you don't get a legend for it)
ggplot(DT) +
geom_density(aes(x = scaled, fill = variable), alpha = 0.2) +
facet_grid(. ~ type)
qplot(data = DT, x = scaled, fill = variable, geom = "density", alpha = 0.2, facets = ~type)
# Histogram
ggplot(DT, aes(x = scaled, fill = variable)) +
geom_histogram(binwidth=.2, alpha=.5, position="identity") +
facet_grid(. ~ type, scales = "free")
qplot(data = DT, x = scaled, fill = variable, alpha = 0.2, facets = ~type)
这篇关于如何在具有融化数据的ggplot中缩放密度图(针对多个变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!