gpt4 book ai didi

r - 如何使用现有计数生成直方图?

转载 作者:行者123 更新时间:2023-11-29 12:32:49 24 4
gpt4 key购买 nike

这可能是一个非常简单的问题,但我已经用谷歌搜索和试验了几个小时,还是找不到答案。这个问题与 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 设置一行并对其计数 1 (!) 来设置数据帧。但肯定有一种使用 SQL 计数的更简单的方法。所以我的问题是:这种更简单的方法是什么?

最佳答案

您可以使用以下方法非常轻松地绘制。例如检查这些。

> 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

关于r - 如何使用现有计数生成直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37183382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com