DEV Community

sravya206888
sravya206888

Posted on

Histogram In R

A histogram represents the frequencies of values of a variable bucketed into ranges.
->Histogram is similar to bar chat but the main difference in this is ,it groups the values into continuous ranges.
->Each bar in histogram represents the height of the number of values present in that range.
->R creates histogram using hist() function. This function takes a vector as an input and uses some more parameters to plot histograms.

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

Code:

v <- c(9,13,21,8,36,22,12,41,31,33,19)
h <- hist(v,xlab = "Weight",col = "pink",border = "blue")
> h
$breaks 
[1] 5 10 15 20 25 30 35 40 45 
$counts 
[1] 2 2 1 2 0 2 1 1 
$density 
[1] 0.03636364 0.03636364 0.01818182 0.03636364 
0.00000000 0.03636364 0.01818182 
[8] 0.01818182 
$mids 
[1] 7.5 12.5 17.5 22.5 27.5 32.5 37.5 42.5 
$xname 
[1] "v" 
$equidist 
[1] TRUE 
attr(,"class") 
[1] "histogram"
Enter fullscreen mode Exit fullscreen mode

->To give a specific value of some range in X axis and Y axis, we can use "xlim" and "ylim" parameters.
By using this we can get the width of each bar using breaks.

Below is the example code:
Code:

v <- c(9,13,31,8,31,22,12,31,35)
hist(v,xlab = "Weight",col = "light green",
border = "red", xlim = c(0,40), ylim = c(0,5),breaks = 5)
Enter fullscreen mode Exit fullscreen mode

Coming next, I have used the function text() which helps to add text to plot and return values to place the count above each cell.

Code:

h<-hist(mtcars$mpg, breaks=12, col="skyblue4") 
text(h$mids,h$counts,labels = h$counts,adj=c(0.5,-0.5))
Enter fullscreen mode Exit fullscreen mode

Generally, a break parameter tells the number of cells required in
the histogram plot.

code:

x<- c(5,3,5,7,3,6,5)
hist(x,breaks = 4,col="violetred3", ,main="breaks=4" ) 
hist(x,breaks = 10,col="slateblue3",main="breaks=10" )
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs