Create a Bar Chart in Python using Matplotlib

To create a bar chart in Python using Matplotlib:

import matplotlib.pyplot as plt

x_axis = ["value_1", "value_2", "value_3", ...]
y_axis = ["value_1", "value_2", "value_3", ...]

plt.bar(x_axis, y_axis)
plt.title("title name")
plt.xlabel("x_axis name")
plt.ylabel("y_axis name")
plt.show()

Steps to Create a Bar Chart in Python using Matplotlib

Step 1: Install the Matplotlib package

If you haven’t already done so, install the Matplotlib package using this command:

pip install matplotlib

Step 2: Gather the data for the bar chart

Next, gather the data for your bar chart.

For demonstration purposes, let’s use the following dataset:

countrygdp_per_capita
A45000
B42000
C52000
D49000
E47000

The ultimate goal is to display the above data using a bar chart.

Step 3: Create the bar chart in Python using Matplotlib

Finally, use the template below to create the bar chart:

import matplotlib.pyplot as plt

x_axis = ["value_1", "value_2", "value_3", ...]
y_axis = ["value_1", "value_2", "value_3", ...]

plt.bar(x_axis, y_axis)
plt.title("title name")
plt.xlabel("x_axis name")
plt.ylabel("y_axis name")
plt.show()

For our example:

import matplotlib.pyplot as plt

country = ["A", "B", "C", "D", "E"]
gdp_per_capita = [45000, 42000, 52000, 49000, 47000]

plt.bar(country, gdp_per_capita)
plt.title("Country Vs GDP Per Capita")
plt.xlabel("Country")
plt.ylabel("GDP Per Capita")
plt.show()

Run the code in Python, and you’ll get the bar chart.

You can further style the bar chart using this code:

import matplotlib.pyplot as plt

country = ["A", "B", "C", "D", "E"]
gdp_per_capita = [45000, 42000, 52000, 49000, 47000]

colors = ["green", "blue", "purple", "brown", "teal"]
plt.bar(country, gdp_per_capita, color=colors)
plt.title("Country Vs GDP Per Capita", fontsize=14)
plt.xlabel("Country", fontsize=14)
plt.ylabel("GDP Per Capita", fontsize=14)
plt.grid(True)
plt.show()

You’ll now get a styled bar chart, where each country is represented by a different color.

Create a Bar Chart in Python with Pandas DataFrame

So far, you have seen how to create a bar chart using lists.

Alternatively, you can capture the dataset in Python using Pandas DataFrame, and then plot your chart.

Here is the complete code that you may use:

import matplotlib.pyplot as plt
import pandas as pd

data = {
"country": ["A", "B", "C", "D", "E"],
"gdp_per_capita": [45000, 42000, 52000, 49000, 47000],
}
df = pd.DataFrame(data)

colors = ["green", "blue", "purple", "brown", "teal"]
plt.bar(df["country"], df["gdp_per_capita"], color=colors)
plt.title("Country Vs GDP Per Capita", fontsize=14)
plt.xlabel("Country", fontsize=14)
plt.ylabel("GDP Per Capita", fontsize=14)
plt.grid(True)
plt.show()

Run the code, and you’ll get the exact same bar chart that you saw in the previous section.

You may also want to check the guides below for the steps to:

Leave a Comment