R - 使用ggplot2绘制变量与相同变量子集的直方图

时间:2016-01-18 10:02:19

标签: r plot ggplot2 dataframe

我是R和ggplot2的新手。我有一个数据框,我想在其中一个变量上绘制直方图以及相同变量的子集。基本上,我想要做的是以下

ggplot(df, aes(x = w, fill = area)) +
geom_histogram(binwidth = 1, position="dodge") 

其中area是我的df中所有数据点与面积> gt的所有点之间的关系。 0.我找不到格式化数据帧的正确方法来实现这一点。目前,这仅给出了分布区域> 0 vs area = 0.

感谢。

编辑: 它现在如何运作

w = runif(50,min=1,max=5)
area = c(rep(0,25), runif(25))
df = data.frame(w, area)

### Wrong
for (i in 1:50){
  if (df$area[i] > 0) {  
    df$size[i] <- "big" 
  }else {
    df$size[i] <- "small"
  }
}
ggplot(df, aes(x = w, fill = size)) +
geom_histogram(binwidth = 1, position="dodge")

如何以一种允许我绘制所有数据点与大数据点的分布的方式对数据框进行分区?

1 个答案:

答案 0 :(得分:1)

一种方法是复制您的子集并创建一个新的因子列,用于标识“所有”行和“子集”行。然后使用新标签作为fill进行绘图。

# Duplicate the "big" data points and add to the end of the data frame
dfSub <- rbind(df, df[26:nrow(df),])
# Create factor column 
dfSub$group <- as.factor(c(rep("all",50),rep("subset",25)))

ggplot(dfSub, aes(x = w, fill = group)) +
  geom_histogram(binwidth = 1, position="dodge")

Plot