【问题标题】:R - plotting histogram of variable vs subset of same variable with ggplot2R - 用ggplot2绘制变量的直方图与同一变量的子集
【发布时间】:2016-04-23 11:00:00
【问题描述】:

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

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

其中 area 将是我的 df 中的所有数据点与面积 > 0 的所有点。我找不到正确的方法来格式化我的数据框以实现这一点。目前这只给出了分布 area > 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")

如何划分数据框,以便绘制所有数据点与大数据点的分布?

【问题讨论】:

  • 你能举个例子reproducible?。它使其他人更容易帮助您。
  • 创建一个只有大数据的新数据集并覆盖两个 geom_histogram(data=all, ....) + geom_histogram(data=bigone....)

标签: r plot ggplot2 dataframe


【解决方案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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2018-04-03
    • 2021-07-14
    • 2018-03-26
    相关资源
    最近更新 更多