How to create bar graph and histogram in Julia?

Overview

We can plot in Julia using various packages like pyplot, plotly, and so on. Plots.jl is one such package using which we can plot in Julia.

Plots.jl can be installed using the following commands:

import Pkg;
Pkg.add("Plots")

The first command imports the package manager. The second command downloads and installs the package.

To use the package, execute the following command:

using Plots

Bar graph

In Julia, a bar graph is created using the bar() function of the Plots package:

Syntax

using Plots
bar(x, y)

Parameters

  • x: These are the data points along the x dimension.
  • y: These are the data points along the y dimension.

Example

using Plots
x = [1,2,3]
y = [4,5,6]
bar(x,y)
savefig("output/plot.png")

Explanation

  • Line 1: We import the Plots package.
  • Line 3: The x-dimension data points are defined.
  • Line 4: The y-dimension data points are defined.
  • Line 6: A bar graph is created using the bar() function.
  • Line 7: The plot is saved to the local disk as plot.png.

Histogram

We can create a histogram in Julia using the histogram() function of the Plots package.

Syntax

using Plots

histogram(x, nbins, weights, normalize)

Parameters

  • x: These are the data points to be plotted.
  • nbins: This is an integer or vector that defines the number of bins to place the input data points.
  • weights: This is a vector that defines the weights for the data points.
  • normalize: This is a boolean value indicating whether or not to normalize the data points. The default value is false. This denotes that no normalization is performed.

Example

using Plots
data = randn(1000)
histogram(data, nbins=20)
savefig("output/plot.png")

Explanation

  • Line 1: We import the Plots package.
  • Line 3: The data points to be plotted are defined.
  • Line 5: A histogram is created using the histogram() function, where the number of bins is set to 20.
  • Line 6: The plot is saved to the local disk as plot.png.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved