【问题标题】:Plotting a simple histogram in R [closed]在 R 中绘制一个简单的直方图
【发布时间】:2020-06-27 17:22:33
【问题描述】:

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

【问题讨论】:

    标签: r plot histogram


    【解决方案1】:

    这里有两种方法。

    基础 R

    下面的函数创建了绘制直方图所需的结构,这是"histogram" 类的对象。然后为该类的对象调用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)
    

    【讨论】:

      【解决方案2】:

      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 是一个允许对图形和图形进行大量操作的包。

      【讨论】:

        【解决方案3】:
        # 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 )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-25
          • 2014-10-24
          • 1970-01-01
          • 2015-05-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-02
          相关资源
          最近更新 更多