【问题标题】:Barplot visualising check boxes条形图可视化复选框
【发布时间】:2010-06-21 15:54:37
【问题描述】:

如果我们有这样的问题(所有答案都是复选框),我必须做一份调查报告。

What is you favorite cake(s) (please choose more than one):
[] Tiramisù
[] Carrot Cake
[] Cupcake

然后调查软件像这样导出为 CSV:

"username","likes_tiramisu","likes_carrotcake","likes_cupcake"
"test01",1,1,1
"test02",0,1,1
"test03",0,1,0
"test04",0,0,1

我想制作一个条形图,其中每个直方图代表每个蛋糕的频率。 如何组合这样的表格:

"likes_tiramisu"  "likes_carrotcake"  "likes_cupcake"
               1                   3                3

我可以用每列中所有元素的总和来解决它吗? 它在概念上有效吗?

【问题讨论】:

  • I would like to make a barplot where every histogram represent the frequency of every cake. 也许你的意思是...where every *bin* represents frequency...
  • 是的,对不起...我的意思是每个垃圾箱。

标签: r plot


【解决方案1】:

假设您的数据在文件中:survey.csv

然后使用以下命令创建条形图:

#Read in the data
d = read.table("survey.csv", sep=",", header=TRUE)

#Need to skip the username column, so d[,2:4]
#Use apply to calculate the totals in your table
barplot(apply(d[,2:4], 2, sum))

HTH

【讨论】:

  • 科林,谢谢你的提示!!我有一个小问题,因为在专栏中我也有 NA。是否有将NA视为0的命令?
  • 好的,我找到了:barplot(apply(d[,2:4], 2, sum, na.rm=TRUE)) 我越来越喜欢 R
  • 有一个对列求和的专用函数 - colSums。您可以使用colSums(d[,2:4])colSums(d[2:4]) 并使用NA 删除colSums(d[,2:4], na.rm=TRUE)colSums(d[2:4], na.rm=TRUE)
【解决方案2】:

ggplot2 方法如下所示:

library(ggplot2)

data.melt <- melt(data, id = "username")
qplot(variable, value, data = data.melt, geom = "bar", stat = "identity")

【讨论】:

  • 我不知道ggplot2中的melt命令。看起来相当给力!非常感谢这个例子
  • melt() 实际上来自reshape包,由ggplot2加载。
  • 对于更新版本的ggplot2,您必须显式加载reshapereshape2,而不是依赖ggplot2 自动加载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多