Data visualization is a crucial step in data analysis. It helps in understanding patterns, trends, and relationships within data. Matplotlib and Seaborn are two powerful Python libraries that enable effective data visualization.
In this tutorial, we will cover:
Install the libraries if not already installed:
pip install matplotlib seabornImport required libraries:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create a line plot
plt.plot(x, y, label='Sine Wave', color='blue', linestyle='dashed')
# Adding labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot Example')
plt.legend()
plt.show()# Sample data
categories = ['A', 'B', 'C', 'D']
values = [10, 25, 15, 30]
# Create a bar plot
plt.bar(categories, values, color='green')
# Adding labels
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart Example')
plt.show()# Generate random data
data = np.random.randn(1000)
# Create a histogram
plt.hist(data, bins=30, color='purple', edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram Example')
plt.show()Matplotlib provides options to customize plots.
plt.figure(figsize=(8, 5))
plt.plot(x, y, color='red', linewidth=2, marker='o', markersize=5)
plt.xlabel('X-axis', fontsize=12)
plt.ylabel('Y-axis', fontsize=12)
plt.title('Customized Line Plot', fontsize=14)
plt.grid(True)
plt.show()Seaborn simplifies data visualization and provides aesthetically pleasing plots.
# Load sample dataset
df = sns.load_dataset("tips")
# Scatter plot using Seaborn
sns.scatterplot(x='total_bill', y='tip', data=df, hue='sex', style='smoker')
plt.title("Scatter Plot with Seaborn")
plt.show()sns.boxplot(x='day', y='total_bill', data=df, palette="coolwarm")
plt.title("Box Plot Example")
plt.show()correlation_matrix = df.corr()
sns.heatmap(correlation_matrix, annot=True, cmap="coolwarm", linewidths=0.5)
plt.title("Heatmap Example")
plt.show()You can use Matplotlib for fine-tuning plots created with Seaborn.
plt.figure(figsize=(8, 5))
sns.histplot(df['total_bill'], kde=True, bins=20, color='blue')
plt.xlabel('Total Bill')
plt.ylabel('Count')
plt.title('Histogram with KDE using Seaborn')
plt.grid(True)
plt.show()Sign in to join the discussion and post comments.
Sign in