matplotlib
matplotlib
Matplotlib is a plotting library that allows you to create static, animated, and interactive visualizations. It
works well with NumPy and Pandas to plot data efficiently.
1. IMPORT MATPLOTLIB
A line plot is the simplest type of plot and is great for visualizing trends in data.
# Data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y): Plots the x values on the x-axis and y values on the y-axis.
plt.title(): Adds a title to the plot.
plt.xlabel() and plt.ylabel(): Label the axes.
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]
plt.show()
plt.plot(): You can specify label for each line and use different colors.
plt.legend(): Displays the legend to distinguish between multiple lines.
4. Scatter Plot
Scatter plots are useful for visualizing the relationship between two variables.
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.title('Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.show()
5. Bar Chart
Bar charts are ideal for comparing quantities across different categories.
plt.title('Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
plt.bar(categories, values): Creates a bar chart with the given categories and
values.
6. Histogram
Example: Histogram
import numpy as np
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
plt.hist(data, bins): Plots a histogram of the data with a specified number of bins
(intervals).
You can also customize the color and edges of the bars.
7. Pie Chart
plt.title('Pie Chart')
plt.show()
plt.pie(): Creates a pie chart where you can specify the labels, colors, and other
parameters.
autopct: Displays the percentage on each slice.
startangle: Rotates the start angle for better visualization.
8. Subplots
You can create multiple plots in the same figure using subplots.
Example: Subplots
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.show()
You can customize your plots in various ways, like changing line styles, colors, and adding grid
lines.
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.show()
Once you're happy with your plot, you can save it to a file.
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.title('Save this Plot')
plt.show()