Chart.js Bar Chart
A bar chart is a statistical chart whose variable is represented by the length of a rectangle.
Bar charts are used to compare two or more values (at different times or under different conditions); with only one variable, they are typically used for analyzing smaller datasets.
The bar chart's type The attribute is bar, and type describes the chart type.
const config = {
type: 'bar',
data: data,
options: {
scales: {
y: {
beginAtZero: true
}
}
},
};
Next, let's create a simple bar chart:
Example
const
ctx
=
document.
getElementById
(
'myChart'
)
;
const
labels
=
[
'January'
,
'February'
,
'March'
,
'April'
,
'May'
,
'June'
,
'July'
]
;
// Set the corresponding labels on the X axis
const
data
=
{
labels
:
labels
,
datasets
:
[
{
label
:
'My First Bar Chart'
,
data
:
[
65
,
59
,
80
,
81
,
56
,
55
,
40
]
,
backgroundColor
:
[
// Set the background color of each bar
'rgba(255, 99, 132, 0.2)'
,
'rgba(255, 159, 64, 0.2)'
,
'rgba(255, 205, 86, 0.2)'
,
'rgba(75, 192, 192, 0.2)'
,
'rgba(54, 162, 235, 0.2)'
,
'rgba(153, 102, 255, 0.2)'
,
'rgba(201, 203, 207, 0.2)'
]
,
borderColor
:
[
// Set the border color of each bar
'rgb(255, 99, 132)'
,
'rgb(255, 159, 64)'
,
'rgb(255, 205, 86)'
,
'rgb(75, 192, 192)'
,
'rgb(54, 162, 235)'
,
'rgb(153, 102, 255)'
,
'rgb(201, 203, 207)'
]
,
borderWidth
:
1
// Set the line width
}
]
}
;
const
config
=
{
type
:
'bar'
,
// Set the chart type
data
:
data
,
// Set the data set
options
:
{
scales
:
{
y
:
{
beginAtZero
:
true
// Set the y axis to start from 0
}
}
}
,
}
;
const
myChart
=
new
Chart
(
ctx
,
config
)
;
Try it »
The output of the above example is:
Horizontal Bar Chart
A horizontal bar chart is a variant of the vertical bar chart, often used to display data trends and to compare multiple datasets side by side.
To create a horizontal bar chart, set the indexAxis property in the options object to y; the default value of indexAxis is x.
Example
const
ctx
=
document.
getElementById
(
'myChart'
)
;
const
labels
=
[
'January'
,
'February'
,
'March'
,
'April'
,
'May'
,
'June'
,
'July'
]
;
// Set the corresponding labels on the X axis
const
data
=
{
labels
:
labels
,
datasets
:
[
{
axis
:
'y'
,
label
:
'My First Bar Chart'
,
data
:
[
65
,
59
,
80
,
81
,
56
,
55
,
40
]
,
fill
:
false
,
backgroundColor
:
[
// Set the background color of each bar
'rgba(255, 99, 132, 0.2)'
,
'rgba(255, 159, 64, 0.2)'
,
'rgba(255, 205, 86, 0.2)'
,
'rgba(75, 192, 192, 0.2)'
,
'rgba(54, 162, 235, 0.2)'
,
'rgba(153, 102, 255, 0.2)'
,
'rgba(201, 203, 207, 0.2)'
]
,
borderColor
:
[
// Set the border color of each bar
'rgb(255, 99, 132)'
,
'rgb(255, 159, 64)'
,
'rgb(255, 205, 86)'
,
'rgb(75, 192, 192)'
,
'rgb(54, 162, 235)'
,
'rgb(153, 102, 255)'
,
'rgb(201, 203, 207)'
]
,
borderWidth
:
1
// Set the line width
}
]
}
;
const
config
=
{
type
:
'bar'
,
// Set the chart type
data
:
data
,
// Set the data set
options
:
{
indexAxis
:
'y'
,
}
}
;
const
myChart
=
new
Chart
(
ctx
,
config
)
;
Try it »
The output of the above example is: