分组条图的频率数据框

  • 本文关键字:频率 数据 r
  • 更新时间 :
  • 英文 :


我正在尝试使用ggplot2创建一个分组的条形图(但可能是其他软件包)。我意识到还有其他几篇与此相似的帖子,但是我找不到任何回答我的特定问题的东西,因此,如果似乎多余的话,我深表歉意。搜索其他问题和答案,我制作了以下代码:

### To remove unwanted rows from the larger data set###
NestPatch=NestPatch[,c(3,34)]
### Reshape data frame ####
dfm <- melt(NestPatch[,c("VOR2Binned", "Factor")],id.vars = 1)

我想在x轴上进行vor2bin,y上的频率和由因子变量(0或1)分组的vor2binned,我想将其重命名为使用和随机的。

这是我的示例数据:

Factor VOR2Binned   
0   3
1   3
0   3
1   3
0   2
1   2
1   3
0   2
1   3
0   2
0   3
1   3
0   3
1   3
0   3
1   3
1   2
0   3
0   0

i最终使用上述代码获得以下订购的数据框。

VOR2Binned   variable   value
0   Factor  0
0   Factor  0
0   Factor  0
0   Factor  0
0   Factor  0
2   Factor  1
2   Factor  0
2   Factor  0
2   Factor  0
2   Factor  1
2   Factor  0
2   Factor  0
2   Factor  0
2   Factor  0
2   Factor  0
2   Factor  0
3   Factor  0
3   Factor  1
3   Factor  1

如果我继续

    #### Plot ####
   ggplot(dfm,aes(x = VOR2Binned,y = variable)) + 
  geom_bar(aes(fill = value),stat = "identity",position = "dodge") + 
  scale_y_log10()

我在eval(Expr,Envir,Enclos)中获得"错误":对象'未找到的因素'。

我认为我错过了开发每个vor2binned类的频率的步骤。

如果您不介意使用data.table ...

# generate your sample data
require(data.table)
dt <- data.table(structure(list(
Factor = c(0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 
1L, 1L, 0L, 0L), VOR2Binned = c(3L, 3L, 3L, 3L, 2L, 2L, 3L, 2L, 3L, 2L, 
3L, 3L, 3L, 3L, 3L, 3L, 2L, 3L, 0L)), .Names = c("Factor","VOR2Binned"), 
row.names = c(NA, -19L), class = c("data.table", "data.frame")))
# count occurrences for each VOR2Binned
dt[, Frequency := .N, by=.(VOR2Binned, Factor)]
# let's make sure column Factor is really a factor
dt$Factor <- as.factor(dt$Factor)
# change name to Used and Available
levels(dt$Factor) <- c("Used", "Available")
# let's ggplot it!
ggplot(dt) + geom_col(aes(VOR2Binned, Frequency, fill=Factor),
                       position="dodge")

好吧,当然,在此工作数小时后,我找到了一种替代方法来在发布问题后瞬间做到这一点。

dfm <- melt(NestPatch[,c("VOR2Binned", "Factor")],id.vars = 3)
dfm <-with(NestPatch, table(VOR2Binned, Factor)) 
tbl <- with(NestPatch, table(Factor, VOR2Binned)); barplot(tbl, beside = TRUE, legend = TRUE) 

使用的可用图

我缺少构建数据表的步骤。

现在这足以可视化数据,但是如果有人能有所帮助,我仍然想弄清楚如何使用ggplot做到这一点。另外,如果有人知道如何从1和0的当前因子代码中修改传奇,则可以非常感谢。预先感谢。

最新更新