لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

Python Data Science Matplotlib Bars Creating Bar Graphs

How to Create Bar Graph?

Matplotlib Bars: Creating Bar Graphs

The bar() function is used with Pyplot to draw bar graphs.

Example 1: Draw 6 bars

Code

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D", "E", "F"])
y = np.array([4, 8, 2, 10, 13, 17])

plt.bar(x,y)
plt.show()

the output will be


The bar() function takes arguments which describes the layout of the bars.

The categories and their values are represented by the first and second argument as arrays.

Example 2: Draw bar graph for fruits and their units sold per hour at a super store.

Code

import matplotlib.pyplot as plt
import numpy as np

x = ["ORANGES", "APPLES", "BANANAS", "MANGOES"]
y = [400, 350, 500, 600]

plt.bar(x, y)
plt.show()

the output will be


Horizontal Bars

If you want the bars to be displayed horizontally instead of vertically, use the barh() function

Example 3: Draw 4 horizontal bars.

Code

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([5, 8, 2, 10])

plt.barh(x, y)
plt.show()

the output will be


Bar Color

The bar() and barh() takes the keyword argument color to set the color of the bars.

Example 4: Draw 4 red bars.

Code

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([5, 8, 3, 10])

plt.bar(x, y, color = "red")
plt.show()

the output will be


Color Names

You can use any of the 140 supported color names.

Example 5: Draw 4 "green" bars.

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([5, 8, 3, 10])

plt.bar(x, y, color = "green")
plt.show()

the output will be


Color Hex

You can also use Hexadecimal color values.

Example 6: Draw 4 bars with a beautiful hotpink color.

Code

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([4, 8, 7, 10])

plt.bar(x, y, color = "#ff69b4")
plt.show()

the output will be


Bar Width

You can specify the bar width. The bar() takes the keyword argument width to set the width of the bars.

Example 7: Draw 4 very thin bars.

Code

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([4, 8, 7, 10])

plt.bar(x, y, width = 0.1, color="red")
plt.show()

the output will be


Bar Height

The barh() takes the keyword argument height to set the height of the bars.

Example 8: Draw 4 very thin bars.

Code

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.barh(x, y, height = 0.1, color="green")
plt.show()

the output will be