We can create bar charts using Matplotlib. A bar chart represents values as vertical bars, where the position of each bar indicates the value it represents. Matplotlib aims to make the transformation of data into bar charts as easy as possible.
Matplotlib Vertical Bar Graph
import matplotlib.pyplot as plt
x = ['Python', 'C++', 'Java', 'Dart', 'C#', 'JavaScript']
y = [51, 62, 63, 54, 65,45]
plt.bar(x, y, align='center', alpha=0.5)
plt.title("Bar Chart", fontdict={'family': 'monospace', 'color': 'red', 'weight': 'bold', 'size': 16}, loc='center')
plt.xlabel('Programming Languages')
plt.ylabel('Scores')
plt.show()
Matplotlib Horizontal Bar Chart
import matplotlib.pyplot as plt
x = ['Python', 'C++', 'Java', 'Dart', 'C#', 'JavaScript']
y = [51, 62, 63, 54, 65, 65]
plt.barh(x, y, align='center', alpha=0.5)
plt.title("Bar Chart", fontdict={'family': 'monospace', 'color': 'red', 'weight': 'bold', 'size': 16}, loc='center')
plt.xlabel('Programming Languages')
plt.ylabel('Scores')
plt.show()
Bar Graph Comparison in Matplotlib
import numpy as np
import matplotlib.pyplot as plt
# Data to plot
n = 4
A_values = [800, 655, 540, 265]
B_values = [950, 562, 454, 620]
# Create plot
fig, ax = plt.subplots()
index = np.arange(n)
bar_width = 0.35
opacity = 0.8
bar_A = plt.bar(index, A_values, bar_width, alpha=opacity, color='r', label='Angola')
bar_B = plt.bar(index + bar_width, B_values, bar_width, alpha=opacity, color='y', label='Brazil')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Statistics by Country')
plt.xticks(index + bar_width / 2, ('A', 'B', 'C', 'D'))
plt.legend()
plt.show()
Stacked Bar Graph in Matplotlib
import matplotlib.pyplot as plt
# Data to plot
x = ['A', 'B', 'C', 'D']
y1 = [2100, 1120, 1110, 2130]
y2 = [1120, 1125, 1115, 1125]
# Plot stacked bar graph
plt.bar(x, y1, color='r')
plt.bar(x, y2, bottom=y1, color='y')
plt.title("Stacked Bar Chart")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.show()
This guide provides a clear and structured way to create bar charts using Matplotlib. You can modify these examples to fit your specific data visualization needs.
Copyright Statement: Unless stated otherwise, all articles are original to this site, please credit the source when sharing.
Article link:http://pybeginners.com/python-data-manipulation/how-to-create-a-bar-chart-in-matplotlib/
License Agreement:Attribution-NonCommercial 4.0 International License