Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

R language histogram


May 12, 2021 R language tutorial


Table of contents


The histogram represents how often the values of variables are stored in the range. A histogram is similar to a bar chart, but the difference is that the values are grouped into consecutive ranges. E ach bar in the histogram represents the height of the number of values present in the range.

The R language uses the hist() function to create histograms. T his function uses vectors as inputs and uses some more parameters to draw histograms.

Grammar

The basic syntax for creating histograms in the R language is -

hist(v,main,xlab,xlim,ylim,breaks,col,border)

The following is a description of the parameters used -

  • v is a vector that contains the values used in histograms.

  • Main represents the title of the chart.

  • Col is used to set the color of the bar.

  • Border is used to set the border color for each bar.

  • xlab is used to give a description of the x-axis.

  • xlim specifies the range of values on the x-axis.

  • ylim specifies the range of values on the y-axis.

  • Break is used to refer to the width of each bar.

Cases

Create a simple histogram using input vector, label, col, and boundary parameters.


The script given below creates and saves the histogram in the current R-language working directory.

# Create data for the graph.
v <-  c(9,13,21,8,36,22,12,41,31,33,19)

# Give the chart file a name.
png(file = "histogram.png")

# Create the histogram.
hist(v,xlab = "Weight",col = "yellow",border = "blue")

# Save the file.
dev.off()

When we execute the code above, it produces the following results -
R language histogram

The range of X and Y values

To specify the range of values allowed on the X and Y axes, we can use the xlim and ylim parameters.

The width of each bar can be determined by using intervals.

# Create data for the graph.
v <- c(9,13,21,8,36,22,12,41,31,33,19)

# Give the chart file a name.
png(file = "histogram_lim_breaks.png")

# Create the histogram.
hist(v,xlab = "Weight",col = "green",border = "red", xlim = c(0,40), ylim = c(0,5),
   breaks = 5)

# Save the file.
dev.off()

When we execute the code above, it produces the following results -

R language histogram