如何使用已存在的计数生成直方图?

时间:2016-05-12 09:53:20

标签: r postgresql count bar-chart

这可能是一个非常简单的问题,但我现在正在谷歌搜索和试验几个小时,但却无法找到答案。这个问题与How to Plot a Pre-Binned Histogram In R的问题不同,因为这是关于调整bin大小而不是使用预先计算的计数。

我将数据从PostgreSQL表中拉入R:

mystuff<-sqldf("select foo, count(bar) from mytable group by foo order by count desc;")

mystuff提供以下数据框内容:

     foo     count
1    gamma   39535
2    delta   21053
3    alpha   17919
4    beta    14930
数据库中的

foo和bar都是字符串。

str(mystuff)
'data.frame':   9 obs. of  2 variables:
 $ foo: chr  "alpha" "beta" "gamma" "delta" ...
 $ count : num  17919 14930 39535 21053 4262 ...

我当时想要做的是绘制一个显示每个foo频率的条形图(我认为条形图在这里是正确的,而不是直方图)。但是当然R坚持做自己的foo计数,每个类别都会达到1。我想要它做的是使用我认真提供的计数。

我使用以下方法让它工作:

mystuff<-sqldf("select foo, 1 as count from mytable;")
mystuff$foo<-as.factor(mystuff$foo)
with(mystuff, Barplot(letter, xlab="foo", ylab="Frequency"))

换句话说,通过为每个foo设置一行数据帧,并为其设置一个计数(!)。但肯定必须有一种更简单的方法来使用SQL计数。所以我的问题是:这更简单的方法是什么?

2 个答案:

答案 0 :(得分:2)

您可以使用以下方法进行非常精细的绘图。例如,检查这些。

> x <- data.frame(foo = letters[1:5],count = runif(5,1,10))
> 
> x
  foo    count
1   a 8.788269
2   b 3.832541
3   c 1.964557
4   d 9.505890
5   e 2.924173


 barplot(height = x$count,names.arg = x$foo,)

enter image description here

或使用ggplot2

library(ggplot2)
ggplot(x,aes(foo,count))+geom_bar(stat="identity")

enter image description here

答案 1 :(得分:1)

require(ggplot2)

d <- data.frame(foo = as.factor(seq(1:50)),count = abs(round(rnorm(50)*10)))
ggplot(data=d,aes(x=foo,y=count))+geom_bar(stat="identity")   

enter image description here

相关问题