Data Visualization with Matplotlib
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 267 wordsLearn how to create compelling data visualizations in Python using Matplotlib, including line plots, bar charts, and scatter plots.
Data visualization is crucial for understanding and presenting data. This guide covers creating compelling visualizations in Python using Matplotlib, including line plots, bar charts, and scatter plots.
First, install the Matplotlib library.
pip install matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.title("Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Line plots with multiple lines.
x = [1, 2, 3, 4, 5]
y1 = [2, 3, 5, 7, 11]
y2 = [1, 4, 6, 8, 10]
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.title("Multiple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()
labels = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
plt.bar(labels, values)
plt.title("Bar Chart")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.show()
Horizontal bar charts.
plt.barh(labels, values)
plt.title("Horizontal Bar Chart")
plt.xlabel("Values")
plt.ylabel("Categories")
plt.show()
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
plt.title("Scatter Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Scatter plots with different sizes and colors.
sizes = [50, 100, 200, 300, 400]
colors = ['red', 'blue', 'green', 'yellow', 'purple']
plt.scatter(x, y, s=sizes, c=colors, alpha=0.5)
plt.title("Custom Scatter Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
plt.plot(x, y, label="Line")
plt.scatter(x, y, label="Points", color='red')
plt.legend()
plt.grid(True)
plt.show()
plt.plot(x, y)
plt.title("Line Plot")
plt.savefig("line_plot.png")
Save plots with custom DPI and format.
plt.plot(x, y)
plt.title("High Resolution Plot")
plt.savefig("line_plot.png", dpi=300, format='png')
Matplotlib is a powerful tool for data visualization in Python. Practice creating different types of plots and customizing them to effectively present your data.