How to Create a Matplotlib Bar Chart from a Pandas DataFrame in Python?

Estimated read time 2 min read

Matplotlib is a popular data visualization library in Python, and Pandas is a popular library for data manipulation and analysis. Pandas provides an easy way to load data from various sources and perform various operations on it, and Matplotlib provides a way to create different types of charts, including bar charts.

Here’s how you can create a bar chart from a Pandas DataFrame using Matplotlib in Python:

import pandas as pd
import matplotlib.pyplot as plt

# create a sample dataframe
data = {'Country': ['USA', 'Canada', 'Mexico', 'Brazil', 'Argentina'],
        'GDP': [21.44, 1.65, 1.27, 2.05, 0.45]}
df = pd.DataFrame(data)

# create a bar chart
plt.bar(df['Country'], df['GDP'])

# set the chart title and axis labels
plt.title('GDP by Country')
plt.xlabel('Country')
plt.ylabel('GDP (trillions USD)')

# display the chart
plt.show()

In this example, we first import the required libraries: Pandas and Matplotlib. We then create a sample DataFrame called df with two columns: Country and GDP. We then use the plt.bar function to create a bar chart using the Country column as the x-axis and the GDP column as the y-axis.

Next, we set the chart title and axis labels using the plt.title, plt.xlabel, and plt.ylabel functions. Finally, we display the chart using the plt.show function.

You can customize the chart by using various parameters of the plt.bar function, such as color, width, edgecolor, linewidth, and so on. You can also use other types of charts in Matplotlib, such as line charts, scatter plots, and histograms, by using the appropriate functions.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply