在R中绘制简单的直方图

在R中绘制简单的直方图,r,plot,histogram,R,Plot,Histogram,我需要在Rstudio中绘制一个直方图,其中的值为:1 2 3 4。其频率分别为0.20.50.20.1。 我怎么做?库(ggplot2) df这里有两种方法 基尔 下面的函数创建绘制直方图所需的结构,直方图是一个类为“直方图”的对象。然后为该类的对象调用plot方法 make_hist <- function(x, y, plot = TRUE){ breaks <- seq(min(x) - 0.5, max(x) + 0.5, by = 1) counts <-

我需要在Rstudio中绘制一个直方图,其中的值为:1 2 3 4。其频率分别为0.20.50.20.1。 我怎么做?

库(ggplot2)

df这里有两种方法

基尔 下面的函数创建绘制直方图所需的结构,直方图是一个类为“直方图”
的对象。然后为该类的对象调用
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)

数据。

x <- 1:4
y <- scan(text = "0.2 0.5 0.2 0.1")
df1 <- data.frame(x, y)
x
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)
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)