【问题标题】:One Vector to DataFrame for use in ggplot histogram in R一个向量到 DataFrame,用于 R 中的 ggplot 直方图
【发布时间】:2015-07-02 00:42:42
【问题描述】:

我正在尝试仅将一个向量转换为数据框。我最终将使用 ggplot 的数据框来创建频率直方图。这是我到目前为止所拥有的......

library(ggplot2)

#This is my vector for prime numbers
prime <- c(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97)

#In order to convert it to a data frame, I tried this method
data <- data.frame(numbers=1:100,prime)

#This is the title of my histogram
main <-"Frequency of Prime Numbers"

#This is what I tried to use to plot the histogram
ggplot(data, aes(x=numbers)) +  geom_histogram() +ggtitle(main)

我能够为这些质数生成频率图,但是读取的频率是 3 和 4,而质数应该以 1 的频率读取,而其他一切都应该以频率读取0。

我想我可能错误地将向量转换为数据框,但我似乎不知道如何仅转换一个向量。我已经看到了多个关于转换两个向量或具有两个变量的列表等的问题,但仅在一个向量上什么都没有......

我想我的问题与我如何首先将向量转换为数据框有关。那是对的吗?如果是这样,为什么我的情节读取计数为 3 和 4,而不是频率为 1 的素数?

有什么帮助吗?

谢谢!

【问题讨论】:

  • 我对你的问题不是很清楚,但是你想要像freq &lt;- rep(0, 100); freq[prime] &lt;- 1这样的东西
  • @Pascal,每个素数的频率为 1,但绘图没有显示。相反,该图显示了 3 和 4 的频率,这对我来说没有意义。
  • 使用geom_histogram函数的参数binwidth来调整bin的大小,即binwidth = 1
  • @Pascal,我试过了,现在它使所有数字的频率为 1,而不仅仅是素数..
  • 是的,因为你想要 100 个“素数”值,但实际长度是 25。所以它们被回收了。这就是为什么你得到 3 或 4 作为频率

标签: r vector ggplot2 histogram


【解决方案1】:
library(ggplot2)

prime <- c(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97)

data <- as.data.frame(prime)

main <-"Frequency of Prime Numbers"

ggplot(data, aes(x=prime)) +  geom_histogram(binwidth = 1) + ggtitle(main)

【讨论】:

  • 我明白你所说的值被回收是什么意思。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多