R:创建ggplot直方图以镜像freq()函数

时间:2017-06-09 11:54:29

标签: r ggplot2 frequency-distribution

我正在尝试使用ggplot创建一个条形图(或直方图)来镜像freq包中的descr函数(其中变量中的每个离散值都在其中有自己的列)频率图,x-ais标记以每个值为中心),但我在使这个工作时遇到一些麻烦。

这是我正在尝试创建的(但使用ggplot以便我可以使用其漂亮的图形):

library(ggplot2)
library(descr)

variable <- c(0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 7)
df <- data.frame(variable)
freq(df$variable)

这是我尝试(并且失败)在ggplot中做同样的事情:

histo.variable <- ggplot(df, aes(x = variable)) + # create histogram
  geom_bar(stat = "bin") +
  xlab("Variable Value") +
  ylab("Count") +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10))
histo.variable

如您所见,条形图不以刻度线为中心。 (此外,摆脱栏之间的小半线也很棒。)

感谢任何可以提供帮助的人!

1 个答案:

答案 0 :(得分:0)

也许是这样的:

ggplot(df, aes(x = variable)) + 
  geom_histogram(aes(y = ..density..),      
                 binwidth = 1,
                 colour = "blue", fill = "lightblue")

freq