简体   繁体   English

给定变量或数据列的R直方图图密度

[英]R histogram plot density for a given variable or column of data

I have a data set with a column for age and a corresponding column with lung capacity. 我有一个数据集,其中有一个年龄列和一个对应的肺活量列。 How can I create a histogram showing the distribution of lung capacity with respect to age? 如何创建直方图来显示肺活量随年龄的分布?

Here is an example of what the data looks like. 这是数据外观的一个示例。 I actually want to compare the distributions for those who don't smoke with those who do: 我实际上是想比较不吸烟者和不吸烟者的分布:

Caes Age Gender Smoke Height FEV

0 16 1 0 64.8 2.65

0 12 0 0 60.5 2.27

1 19 1 0 71.7 4.29

0 15 0 0 64.8 2.52

Histograms are usually used when you have a single vector (like lung capacity) and you want to show the distribution of values: 当您有单个矢量(例如肺活量)并且想要显示值的分布时,通常使用直方图:

library(ggplot2)
foo <- data.frame(age=runif(1000,min=10,max=50), capacity=rnorm(1000,mean=10))
ggplot(foo, aes(capacity))+geom_histogram(fill="blue")

在此处输入图片说明

If you want to plot the relationship between two variables, scatter plot might be a better choice: 如果要绘制两个变量之间的关系,散点图可能是更好的选择:

ggplot(foo, aes(age, capacity))+geom_point(color="blue")

在此处输入图片说明

Thanks for the responses. 感谢您的答复。 I realized that I wanted a barplot rather than a histogram. 我意识到我想要的是条形图而不是直方图。 Here is the solution that I came up with: 这是我想出的解决方案:

smoke=read.csv("SmokingEffect.csv",header=TRUE)
smokes=subset(smoke,select=c(Age,Smoke,FEV))
library(plyr)
smokesmeans <- ddply(smokes, c("Age","Smoke"), summarize, mean=mean(FEV),
sem=sd(FEV)/sqrt(length(FEV)))
smokesmeans <- transform(smokesmeans, lower=mean-sem, upper=mean+sem)
smokesmeans[,2] <- sapply(smokesmeans[,2], as.character)
library(ggplot2)
plotation <- qplot(x=Age, y=mean, fill=Smoke, data=smokesmeans, 
geom="bar",stat="identity",position="dodge",main="distribution of FEV",
ylab="mean FEV")
plotation <- plotation + geom_errorbar(aes(ymax=upper,
ymin=lower), position=position_dodge(0.9), data=smokesmeans)
png(myplot.png)
plotation
dev.off()

The output looks like this: 输出看起来像这样:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM