Matplotlib Pandas Guide
Matplotlib Pandas Guide
Visualization Examples
1. Line Plot - Stock Price Trend
import pandas as pd
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.plot(df['Date'], df['Price'], marker='o')
plt.title('Stock Price Trend 2023')
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.grid(True)
plt.show()
plt.figure(figsize=(8, 6))
df.plot(kind='bar', x='Month', y='Sales')
plt.title('Monthly Sales Performance')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
plt.show()
3. Scatter Plot - Height vs Weight
# Generate sample data
np.random.seed(42)
n = 50
height = np.random.normal(170, 10, n)
weight = height * 0.7 + np.random.normal(0, 5, n)
df = pd.DataFrame({'Height': height, 'Weight': weight})
plt.figure(figsize=(8, 6))
plt.scatter(df['Height'], df['Weight'])
plt.title('Height vs Weight Correlation')
plt.xlabel('Height (cm)')
plt.ylabel('Weight (kg)')
plt.show()
plt.figure(figsize=(8, 6))
df['Age'].hist(bins=30, edgecolor='black')
plt.title('Age Distribution')
plt.xlabel('Age')
plt.ylabel('Frequency')
plt.show()
plt.figure(figsize=(8, 6))
df.boxplot()
plt.title('Product Price Distribution')
plt.ylabel('Price ($)')
plt.show()
plt.figure(figsize=(8, 8))
plt.pie(df['Share'], labels=df['Company'], autopct='%1.1f%%')
plt.title('Market Share Distribution')
plt.show()
plt.figure(figsize=(10, 6))
df.plot(kind='area', stacked=True)
plt.title('Revenue Streams Over Time')
plt.xlabel('Date')
plt.ylabel('Revenue ($K)')
plt.show()
plt.figure(figsize=(10, 6))
df.plot(marker='o')
plt.title('Temperature Comparison Across Cities')
plt.xlabel('Date')
plt.ylabel('Temperature (°C)')
plt.grid(True)
plt.show()
plt.tight_layout()
plt.show()
11. Heatmap - Correlation Matrix
# Generate correlated data
np.random.seed(42)
n = 100
data = {
'A': np.random.normal(0, 1, n),
'B': np.random.normal(0, 1, n),
'C': np.random.normal(0, 1, n),
'D': np.random.normal(0, 1, n)
}
df = pd.DataFrame(data)
correlation = df.corr()
plt.figure(figsize=(8, 6))
plt.imshow(correlation, cmap='coolwarm', aspect='auto')
plt.colorbar()
plt.xticks(range(len(correlation.columns)), correlation.columns)
plt.yticks(range(len(correlation.columns)), correlation.columns)
plt.title('Correlation Heatmap')
plt.show()
# Plot components
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(12, 10))
# Original
ts.plot(ax=ax1)
ax1.set_title('Original Time Series')
plt.tight_layout()
plt.show()
To run these examples, make sure you have the following imports:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np