Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to generate statistical graphs using Python?
Python has an amazing graph plotting library called matplotlib. It is the most popular graphing and data visualization module for Python. You can start plotting graphs using just 3 lines of code!
Basic Line Plot
Here's how to create a simple line plot ?
from matplotlib import pyplot as plt # Plot coordinates (1,4), (2,5), (3,1) plt.plot([1, 2, 3], [4, 5, 1]) # Display the plot plt.show()
Adding Labels and Title
You can enhance your plot with descriptive labels and a title ?
from matplotlib import pyplot as plt
plt.plot([1, 2, 3], [4, 5, 1])
# Add labels and title
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('My Graph')
plt.show()
Styling Your Plots
You can customize the appearance by adding line width, colors, and legends ?
from matplotlib import pyplot as plt
# Create a styled plot with legend
plt.plot([1, 2, 3], [4, 5, 1], linewidth=2, label='Data Series 1')
plt.plot([1, 2, 3], [2, 3, 4], linewidth=2, label='Data Series 2')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Styled Graph with Legend')
plt.legend()
plt.show()
Different Chart Types
Matplotlib supports various chart types for different data visualization needs ?
import matplotlib.pyplot as plt
# Sample data
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]
# Create a bar chart
plt.figure(figsize=(10, 4))
# Bar chart
plt.subplot(1, 2, 1)
plt.bar(categories, values)
plt.title('Bar Chart')
# Pie chart
plt.subplot(1, 2, 2)
plt.pie(values, labels=categories, autopct='%1.1f%%')
plt.title('Pie Chart')
plt.tight_layout()
plt.show()
Statistical Plots
For statistical analysis, you can create histograms and scatter plots ?
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
data = np.random.normal(100, 15, 1000)
x = np.random.randn(100)
y = np.random.randn(100)
plt.figure(figsize=(10, 4))
# Histogram
plt.subplot(1, 2, 1)
plt.hist(data, bins=30, alpha=0.7)
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')
# Scatter plot
plt.subplot(1, 2, 2)
plt.scatter(x, y, alpha=0.6)
plt.title('Scatter Plot')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.tight_layout()
plt.show()
Conclusion
Matplotlib makes it easy to create statistical graphs in Python with just a few lines of code. You can customize plots with labels, titles, legends, and choose from various chart types like bar charts, pie charts, histograms, and scatter plots for effective data visualization.
