Matplotlib is a popular Python library used for data visualization. It helps us create graphs, charts, and plots to understand data easily.
Use the following command to install Matplotlib:
pip install matplotlib
The most common way to import Matplotlib is:
import matplotlib.pyplot as plt
A line plot shows trends over time.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.title("Simple Line Plot")
plt.show()
Bar charts are used to compare different categories.
import matplotlib.pyplot as plt
subjects = ['Math', 'Science', 'English']
marks = [85, 90, 78]
plt.bar(subjects, marks)
plt.title("Student Marks")
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.show()
Pie charts show parts of a whole.
import matplotlib.pyplot as plt
sizes = [40, 30, 20, 10]
labels = ['A', 'B', 'C', 'D']
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Pie Chart Example")
plt.show()
Scatter plots show the relationship between two variables.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [5, 7, 4, 8, 6]
plt.scatter(x, y)
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Scatter Plot")
plt.show()
plt.plot(x, y, color='red', linestyle='--', marker='o')
You can save a graph as an image file.
plt.savefig("graph.png")