Related Tags

matplotlib
bar
communitycreator

# How to create horizontal and vertical Bars in Matplotlib Onyejiaku Theophilus Chidalu

### Overview

A bar chart is a diagram in which the numerical values of variables are represented by the height or length of lines or rectangles of equal width. In simpler terms, they present categorical data using rectangular bars. Bars used in this case could be horizontal or vertical. We can plot bar charts with the pyplot module in the Matplot library, matplotlib.

To plot a bar chart, we use the following command:

pyplot.bar(x, y)


Here the x and y parameter values represent the horizontal and vertical axis of the plot, respectively.

It is worth noting that the pyplot.bar function takes more parameter values other than just the x and y axis values. However, it is beyond the scope of this shot to look at the other parameters.

### Plotting a vertical bar chart

A vertical bar represents the data vertically. Hence, its bars are drawn vertically. In such a chart, the data categories are shown on the x-axis while the data values are shown on the y-axis.

### Example

# importing the necessary libraries and modules
import matplotlib.pyplot as plt
import numpy as np

# creating the data values for the vertical y and horisontal x axis
x = np.array(["Oranges", "Apples", "Mangoes", "Berries"])
y = np.array([3, 8, 1, 10])

# using the pyplot.bar funtion
plt.bar(x,y)

# to show our graph
plt.show()
Vertical bar graph

### Explanation

As seen in the code above, we first import the libraries (matplotlib) and the modules (pyplot and numpy) needed to plot a bar chart. With numpy.array(), we create an array of values for the x and y axes. Then, using the pyplot.bar(x, y) function, we create a vertical bar chart with horizontal and vertical values. Lastly, we use the pyplot.show() function to display our graph.

### Plotting a horizontal bar chart

A horizontal bar chart represents the data horizontally. Hence, its bars are drawn horizontally. The data categories are shown on the y-axis, while the data values are shown on the x-axis.

The unique thing about the syntax for the horizontal bar chart is the h after the bar

pyplot.barh(x, y)


### Example

# importing the necessary libraries and modules
import matplotlib.pyplot as plt
import numpy as np

# creating the data values for the vertical y and horisontal x axis
x = np.array(["Oranges", "Apples", "Mangoes", "Berries"])
y = np.array([3, 8, 1, 10])

# using the pyplot.barh funtion for the horizontal bar
plt.barh(x,y)

# to show our graph
plt.show()
Horizontal bar graph

We can see that the only difference between the vertical and horizontal bar charts is their syntax. We use the pyplot.bar() function for a vertical bar chart and the pyplot.barh()` function for a horizontal bar chart.

RELATED TAGS

matplotlib
bar
communitycreator

CONTRIBUTOR Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 