R Histogram using hist() function - r - learn r - r programming
- In this article, you'll learn to create histograms in R using the hist() function. You'll also learn to color them and manipulate other parameters in a histogram.
- Histogram can be created using the hist() function in R programming language.
- This function takes in a vector of values for which the histogram is plotted.
- Let us use the built-in dataset airquality which has Daily air quality measurements in New York, May to September 1973.
- We will use the temperature parameter which has 154 observations in degree Fahrenheit.
Example 1: Simple histogram
- We can see above that there are 9 cells with equally spaced breaks.
- In this case, the height of a cell is equal to the number of observation falling in that cell.
- We can pass in additional parameters to control the way our plot looks.
- Some of the frequently used ones are, main to give the title, xlab and ylab to provide labels for the axes, xlim and ylim to provide range of the axes, col to define color etc.
- Additionally, with the argument freq=FALSE we can get the probability distribution instead of the frequency.
Example 2: Histogram with added parameters
- Note that the y axis is labelled density instead of frequency. In this case, the total area of the histogram is equal to 1.
Return Value of hist()
- The hist() function returns a list with 6 components
- We see that an object of class histogram is returned which has:
- breaks-places where the breaks occur,
- counts-the number of observations falling in that cell,
- density-the density of cells, mids-the midpoints of cells,
- xname-the x argument name and
- equidist-a logical value indicating if the breaks are equally spaced or not.
- We can use these values for further processing.
- In the following example we use the return values to place the counts on top of each cell using the text() function.
Example 3: Use Histogram return values for labels using text()
Defining the Number of Breaks
- With the breaks argument we can specify the number of cells we want in the histogram. However, this number is just a suggestion.
- R calculates the best number of cells. Following are two histograms on the same data with different number of cells.
Example 4: Histogram with different breaks
- In the above figure we see that the actual number of cells plotted is greater than we had specified.
- We can also define breakpoints between the cells as a vector. This makes it possible to plot a histogram with unequal intervals. In such case, the area of the cell is proportional to the number of observations falling inside that cell.