1.
Simple Line Plot
import matplotlib.pyplot as plt # Importing the plotting library
x = [1, 2, 3, 4] # X-axis data points
y = [10, 20, 25, 30] # Y-axis data points
plt.plot(x, y) # Create a line plot with x and y values
plt.title("Simple Line Plot") # Add a title to the plot
plt.xlabel("X-axis") # Label for x-axis
plt.ylabel("Y-axis") # Label for y-axis
plt.show() # Display the plot
🔹 Explanation: This program plots a simple line graph connecting points
(1,10), (2,20), etc. plt.show() must be called to render the plot window.
✅ 2. Simple Scatter Plot
plt.scatter([1, 2, 3, 4], [10, 20, 25, 30]) # Scatter plot of (x, y) points
plt.title("Simple Scatter Plot") # Title for the graph
plt.show() # Display the plot
🔹 Explanation: Each pair (x, y) is shown as a separate dot. Scatter plots
are used to analyze the relationship between two variables.
✅ 3. Pie Chart
labels = ['A', 'B', 'C', 'D'] # Category labels
sizes = [15, 30, 45, 10] # Size of each slice
plt.pie(sizes, labels=labels, autopct='%1.1f%%') # Plot pie chart with
percentage display
plt.title("Pie Chart")
plt.show()
🔹 Explanation: This creates a pie chart with 4 slices. autopct='%1.1f%%'
shows percentages on the chart (like 15.0%).
✅ 4. Box Plot
data = [7, 8, 5, 6, 9, 7, 8, 10, 15, 20]
plt.boxplot(data) # Create a boxplot to visualize data distribution
plt.title("Box Plot") # Title
plt.show()
🔹 Explanation: The boxplot shows median, quartiles, and outliers in the
dataset. It's useful for spotting spread and anomalies.
✅ 5. Matplotlib Grid
plt.plot(x, y) # Line plot
plt.grid(True) # Add gridlines
plt.show()
🔹 Explanation: plt.grid(True) makes it easier to read values from the plot.
✅ 6. Display Images
import numpy as np # Used to generate numerical array
img = np.random.rand(10,10) # 10x10 matrix of random grayscale
values
plt.imshow(img, cmap='gray') # Display the image with grayscale color
map
plt.title("Random Image")
plt.colorbar() # Adds a scale bar
plt.show()
🔹 Explanation: This creates and displays a random grayscale image.
Each pixel gets a random brightness.
✅ 7. Tables
data = [[66386, 174296, 193263, 28924, 19670],
[115046, 57667, 47785, 79854, 20650]]
columns = ('Jan', 'Feb', 'Mar', 'Apr', 'May') # Column headers
rows = ['Tokyo', 'New York'] # Row labels
plt.table(cellText=data, rowLabels=rows, colLabels=columns,
loc='center')
plt.axis('off') # Hide axes
plt.show()
🔹 Explanation: This shows a table inside the plot area with city-wise
monthly data.
✅ 8. Date Handling
import matplotlib.dates as mdates
import datetime
dates = [datetime.datetime(2025, 7, i) for i in range(1, 6)]
values = [1, 3, 2, 5, 4]
plt.plot(dates, values)
plt.gcf().autofmt_xdate() # Format date labels nicely
plt.show()
🔹 Explanation: Plots values against calendar dates. autofmt_xdate() tilts
the date labels so they don’t overlap.
✅ 9. Log Plot
plt.plot([1, 10, 100, 1000], [1, 2, 3, 4])
plt.xscale('log') # Set x-axis to log scale
plt.title("Logarithmic Plot")
plt.show()
🔹 Explanation: This is used when data grows exponentially. It compresses
wide-range x values.
✅ 10. Polar Plot
theta = np.linspace(0, 2*np.pi, 100) # Angle values
r = np.abs(np.sin(5*theta)) # Radius values
plt.polar(theta, r) # Create a polar plot
plt.title("Polar Plot")
plt.show()
🔹 Explanation: This plots data in circular format. Useful for periodic data
like angles, waves, etc.
✅ 11. Visualizing Errors
x = [1, 2, 3, 4]
y = [2, 3, 5, 7]
errors = [0.2, 0.3, 0.2, 0.4]
plt.errorbar(x, y, yerr=errors, fmt='o') # 'o' = circle marker
plt.title("Error Bars")
plt.show()
🔹 Explanation: Shows uncertainty in each data point with error bars
above/below it.
✅ 12. Contour Plot
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.exp(-X**2 - Y**2)
plt.contour(X, Y, Z) # Contour plot for 3D data
plt.title("Contour Plot")
plt.show()
🔹 Explanation: Plots lines of constant value (like elevation on a map).
✅ 13. Histogram
data = np.random.randn(1000) # Random normal data
plt.hist(data, bins=30, density=True) # Histogram with 30 bins
plt.title("Histogram")
plt.show()
🔹 Explanation: Shows how often each range of values occurs.
density=True shows probability density.
✅ 14. Customizing Plot Legends
plt.plot(x, y, label='Line 1')
plt.plot(x, [i*2 for i in y], label='Line 2')
plt.legend(loc='upper left') # Add legend at upper-left
plt.show()
🔹 Explanation: Legends help identify different data series in the same
plot.
✅ 15. Customizing Colorbars
Editimg = np.random.rand(10,10)
plt.imshow(img, cmap='viridis')
plt.colorbar() # Adds scale reference for color intensity
plt.show()
🔹 Explanation: Useful in heatmaps or image data to show the value
range.
✅ 16. Multiple Subplots
plt.subplot(1, 2, 1) # 1 row, 2 columns, 1st plot
plt.plot(x, y)
plt.title("Plot 1")
plt.subplot(1, 2, 2) # 2nd plot
plt.scatter(x, y)
plt.title("Plot 2")
plt.tight_layout() # Avoid overlapping titles
plt.show()
🔹 Explanation: Two plots are shown side-by-side in the same figure
window.
✅ 17. Text and Annotation
plt.plot(x, y)
plt.text(2, 20, "Sample Text", fontsize=12) # Add text
plt.annotate('Max', xy=(4, 30), xytext=(3, 25),
arrowprops=dict(facecolor='black', shrink=0.05)) # Annotate
with arrow
plt.show()
🔹 Explanation: Text helps label key points; annotate() can point to them
with arrows.
✅ 18. Customizing Ticks
plt.plot(x, y)
plt.xticks([1, 2, 3, 4], ['A', 'B', 'C', 'D']) # Rename x-tick labels
plt.show()
🔹 Explanation: Ticks are modified to show custom labels instead of
numbers.
✅ 19. Customizing Matplotlib Styles
plt.style.use('ggplot') # Apply pre-defined ggplot style
plt.plot(x, y)
plt.show()
🔹 Explanation: Styles like 'ggplot', 'seaborn' improve plot appearance
with a single line.