在 R 中绘制一个简单的直方图

Plotting a simple histogram in R

我需要在 Rstudio 中绘制直方图,其中我的值为:1 2 3 4。它们的频率分别为 0.2 0.5 0.2 0.1。 我该怎么做?

library(ggplot2)

df <- data.frame(points= c(1,2,3,4), data = c(0.2, 0.5, 0.2, 0.1))
ggplot(df, aes(x = points, y = data)) + geom_histogram(stat = "identity")

ggplot2 是一个允许对图形和图形进行大量操作的包。

# Plot a histogram and write adequate titles
# Main = Title
# ylab & xlab = Axis title
# breaks how many bars you print

hist(sample, main = "Histogram", ylab= "Number of Observation", xlab="Observation's value", breaks = 100 )

这里有两种方法。

基础 R

下面的函数创建了绘制直方图所需的结构,class "histogram" 的一个对象。然后为 class.

的对象调用 plot 方法
make_hist <- function(x, y, plot = TRUE){
  breaks <- seq(min(x) - 0.5, max(x) + 0.5, by = 1)
  counts <- y*10
  density <- y
  mids <- x
  d <- diff(x)
  equidist <- all(d == d[1])
  h <- list(breaks = breaks,
            counts = counts,
            density = density,
            mids = mids,
            equidist = equidist)
  class(h) <- "histogram"
  if(plot) plot(h)
  invisible(h)
}

make_hist(x, y)

套餐ggplot2

对于问题中的数据集,最好的方法是绘制条形图,列的宽度等于 1,即可能宽度的 100%。

library(ggplot2)

ggplot(df1, aes(x, y)) + geom_col(width = 1)

数据.

x <- 1:4
y <- scan(text = "0.2 0.5 0.2 0.1")
df1 <- data.frame(x, y)