0% found this document useful (0 votes)
2 views14 pages

Matplot

The document contains Python code for generating various types of visualizations using Matplotlib, including line charts, pie charts, bar charts, histograms, and scatter plots, along with an exploratory data analysis (EDA) section for a dataset. Each visualization is accompanied by specific data, customization options, and annotations to enhance clarity. The EDA section includes data loading, missing value handling, outlier detection, and correlation analysis, providing a comprehensive overview of the dataset.

Uploaded by

Anish
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Matplot

The document contains Python code for generating various types of visualizations using Matplotlib, including line charts, pie charts, bar charts, histograms, and scatter plots, along with an exploratory data analysis (EDA) section for a dataset. Each visualization is accompanied by specific data, customization options, and annotations to enhance clarity. The EDA section includes data loading, missing value handling, outlier detection, and correlation analysis, providing a comprehensive overview of the dataset.

Uploaded by

Anish
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Line chart-

import [Link] as plt

# Data
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

temperatures = [30, 32, 31, 35, 34, 36]

# Find maximum temperature and its index


max_temp = max(temperatures)
max_index = [Link](max_temp)

# Create the plot


fig, ax = [Link](figsize=(10, 6))

# Plot line chart with custom color, style, and marker

[Link](days, temperatures,

color='darkorange',

linestyle='-.',
linewidth=2.5,

marker='^',
markersize=10,

markerfacecolor='red',

markeredgecolor='darkred',
markeredgewidth=1.5,

label='Daily Temperature (°C)')

# Label axes

ax.set_xlabel('Day', fontsize=13, fontweight='bold')

ax.set_ylabel('Temperature (°C)', fontsize=13, fontweight='bold')


# Add title
ax.set_title('Daily Temperature Data - Line Chart', fontsize=15,
fontweight='bold')
# Set Y-axis range for better visibility

ax.set_ylim(28, 38)

# Display grid lines

[Link](True, linestyle='--', alpha=0.6, color='gray')


# Highlight maximum temperature with annotation

[Link](f'Max Temp: {max_temp}°C',


xy=(days[max_index], max_temp),

xytext=(days[max_index], max_temp + 0.8),

arrowprops=dict(arrowstyle='->', color='blue', lw=2),


fontsize=11,
color='blue',

fontweight='bold',
ha='center')
# Add legend

[Link](fontsize=11, loc='upper left')


plt.tight_layout()

[Link]('daily_temperature_chart.png', dpi=150)

[Link]()
Pie chart-
import [Link] as plt

# Data
streams = ['Science', 'Commerce', 'Arts', 'IT']

students = [120, 100, 80, 60]

# Find the largest slice index (Science = 120)


max_index = [Link](max(students))
# Explode the largest slice

explode = [0.1 if i == max_index else 0 for i in range(len(students))]


# Custom colors for each slice

colors = ['#4C72B0', '#55A868', '#C44E52', '#FF9F00']

# Create the plot

fig, ax = [Link](figsize=(8, 8))

# Plot pie chart


wedges, texts, autotexts = [Link](

students,
labels=streams,

autopct='%1.1f%%',

explode=explode,
colors=colors,

startangle=140,

pctdistance=0.75,

wedgeprops=dict(edgecolor='white', linewidth=2),

shadow=True)
# Customize label fonts
for text in texts:

text.set_fontsize(13)
text.set_fontweight('bold')

# Customize percentage fonts

for autotext in autotexts:


autotext.set_fontsize(11)
autotext.set_fontweight('bold')

autotext.set_color('white')
ax.set_title('Student Distribution by Stream',

fontsize=16,

fontweight='bold',

pad=20)

# Add legend
[Link](

wedges,
[f'{s} ({n} students)' for s, n in zip(streams, students)],

title='Streams',

title_fontsize=12,
fontsize=11,

loc='lower left',

bbox_to_anchor=(0.0, -0.05))

plt.tight_layout()

[Link]('student_stream_piechart.png', dpi=150, bbox_inches='tight')


[Link]()
Bar chart-import [Link] as plt
import numpy as np

# Data
sources = ['Electricity', 'Gas', 'Solar', 'Others']

units = [300, 150, 100, 50]

# Custom colors
colors = ['#F4D03F', '#E67E22', '#2ECC71', '#95A5A6']
# Find maximum value index

max_index = [Link](max(units))
# Create the plot

fig, ax = [Link](figsize=(10, 6))

# Plot bar chart

bars = [Link](sources, units,

color=colors,
edgecolor='black',

linewidth=1.2,
width=0.5)

# Add value labels on top of each bar

for i, bar in enumerate(bars):


height = bar.get_height()

[Link](bar.get_x() + bar.get_width() / 2,

height + 5,

f'{height} units',

ha='center', va='bottom',
fontsize=11, fontweight='bold', color='black')
# Highlight the largest bar with annotation
[Link]('Highest Consumption',

xy=(sources[max_index], units[max_index]),
xytext=(sources[max_index], units[max_index] + 30),

arrowprops=dict(arrowstyle='->', color='red', lw=2),

fontsize=11, color='red', fontweight='bold',


ha='center')
# Label axes

ax.set_xlabel('Energy Source', fontsize=13, fontweight='bold')


ax.set_ylabel('Units Consumed', fontsize=13, fontweight='bold')

# Title
ax.set_title('Daily Energy Consumption by Source', fontsize=15,
fontweight='bold')
# Grid lines on Y-axis

[Link](True, linestyle='--', alpha=0.7, color='gray')


ax.set_axisbelow(True)
# Y-axis range

ax.set_ylim(0, 370)
# Legend

[Link](bars, sources, title='Energy Sources',

title_fontsize=11, fontsize=10, loc='upper right')

plt.tight_layout()

[Link]('energy_bar_chart.png', dpi=150)
[Link]()
Histogram-import [Link] as plt
import numpy as np

# Simulated energy consumption data (expanded for histogram distribution)


[Link](42)

electricity = [Link](300, 30, 200) # mean=300, std=30

gas = [Link](150, 20, 200)


solar = [Link](100, 15, 200)
others = [Link](50, 10, 200)

# Combine all into one dataset


all_units = [Link]([electricity, gas, solar, others])

# Create the plot

fig, axes = [Link](2, 2, figsize=(12, 9))

[Link]('Daily Energy Consumption — Histogram Distribution',

fontsize=16, fontweight='bold', y=1.01)


datasets = [electricity, gas, solar, others]

names = ['Electricity', 'Gas', 'Solar', 'Others']


colors = ['#F4D03F', '#E67E22', '#2ECC71', '#95A5A6']

mean_vals = [300, 150, 100, 50]


for ax, data, name, color, mean in zip([Link](), datasets, names, colors,
mean_vals):

# Plot histogram

[Link](data, bins=20, color=color, edgecolor='black',

linewidth=0.8, alpha=0.85, label=name)


# Add mean line
[Link](mean, color='red', linestyle='--', linewidth=2, label=f'Mean =
{mean}')
# Labels and title

ax.set_title(f'{name} Consumption', fontsize=13, fontweight='bold')


ax.set_xlabel('Units Consumed', fontsize=11)

ax.set_ylabel('Frequency', fontsize=11)

# Grid
[Link](True, linestyle=':', alpha=0.6)

ax.set_axisbelow(True)

# Legend

[Link](fontsize=10)

plt.tight_layout()
[Link]('energy_histogram.png', dpi=150, bbox_inches='tight')

[Link]()
Scatter plot-import [Link] as plt
import numpy as np

# Simulated hourly energy consumption data (24 hours)


[Link](42)

hours = [Link](1, 25) # Hours 1 to 24

# Simulate consumption values around base means with variation


electricity = [Link](300, 40, 24)
gas = [Link](150, 25, 24)

solar = [Link](100, 20, 24)


others = [Link](50, 10, 24)

# Colors and markers for each source

sources = ['Electricity', 'Gas', 'Solar', 'Others']

datasets = [electricity, gas, solar, others]

colors = ['#F4D03F', '#E67E22', '#2ECC71', '#95A5A6']


markers = ['o', 's', '^', 'D']

# Create the plot


fig, ax = [Link](figsize=(13, 7))

for data, name, color, marker in zip(datasets, sources, colors, markers):

[Link](hours, data,
label=name,

color=color,

marker=marker,

s=100, # Marker size

edgecolors='black',
linewidths=0.8, alpha=0.85)
# Add trend line for each source
z = [Link](hours, data, 1)

p = np.poly1d(z)
[Link](hours, p(hours),

color=color,

linestyle='--',
linewidth=1.5,
alpha=0.7)

# Highlight overall maximum point


all_data = [Link](datasets)

all_hours = [Link](hours, len(datasets))

max_idx = [Link](all_data)

max_hour = all_hours[max_idx]

max_val = all_data[max_idx]
[Link](f'Peak: {max_val:.1f} units\n(Hour {max_hour})',

xy=(max_hour, max_val),
xytext=(max_hour + 1.5, max_val + 10),

arrowprops=dict(arrowstyle='->', color='red', lw=2),

fontsize=10, color='red', fontweight='bold',


bbox=dict(boxstyle='round,pad=0.3', fc='lightyellow', ec='red'))

# Axes labels

ax.set_xlabel('Hour of the Day', fontsize=13, fontweight='bold')

ax.set_ylabel('Units Consumed', fontsize=13, fontweight='bold')

ax.set_title('Daily Energy Consumption — Scatter Plot (Hourly)',


fontsize=15, fontweight='bold')
# X-axis ticks for all 24 hours

ax.set_xticks(hours)
ax.set_xticklabels([f'{h}:00' for h in hours], rotation=45, fontsize=9)

# Grid

[Link](True, linestyle='--', alpha=0.5, color='gray')


ax.set_axisbelow(True)
# Legend

[Link](title='Energy Sources', title_fontsize=12,


fontsize=11, loc='upper right')

plt.tight_layout()

[Link]('energy_scatter_plot.png', dpi=150, bbox_inches='tight')

[Link]()
Eda code-
import pandas as pd

import numpy as np
import [Link] as plt

# Load Dataset

df = pd.read_csv("[Link]")
print(df)
print("Shape of dataset:", [Link])

print("\nColumns:", [Link]())
print("\nData Types:\n", [Link])

# First 5 rows

print("\nFirst 5 rows:\n", [Link]())

# Last 5 rows

print("\nLast 5 rows:\n", [Link]())


# Check missing values

print("\nMissing Values:\n", [Link]().sum())


# Option 1: Mean Imputation (for normally distributed data)

df['Calories'] = df['Calories'].fillna(df['Calories'].mean())

# Option 2: Median Imputation (preferred when outliers exist)


df['Calories'] = df['Calories'].fillna(df['Calories'].median())

# Option 3: Drop rows with missing values (only if very few)

df = [Link]()

# Verify after imputation

print("\nMissing values after imputation:\n", [Link]().sum())


print("\nSummary Statistics:\n", [Link]())
for column in [Link]:
Q1 = df[column].quantile(0.25)

Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1

lower = Q1 - 1.5 * IQR

upper = Q3 + 1.5 * IQR


outliers = df[(df[column] < lower) | (df[column] > upper)]
print(f"\nOutliers in {column}: {len(outliers)}")

# Method 1: All columns at once


[Link]()

[Link]("Histograms of Features")

plt.tight_layout()

[Link]()

# Single column boxplot


[Link]()

[Link](df['Calories'])
[Link]("Boxplot of Calories")

[Link]("Calories")

[Link]()
# Combined boxplot for two columns

[Link]()

[Link]([df['Calories'].dropna(), df['Maxpulse']])

[Link]([1, 2], ['Calories', 'Maxpulse'])

[Link]("Boxplot of Calories and Maxpulse")


[Link]("Values"),[Link]()
correlation = [Link]()

print("\nCorrelation Matrix:\n", correlation)

[Link](figsize=(8, 6))

[Link]([Link], cmap='coolwarm', aspect='auto')

[Link]()

[Link](range(len([Link])), [Link], rotation=45)

[Link](range(len([Link])), [Link])

[Link]("Correlation Heatmap")

plt.tight_layout()

[Link]()

# Duration vs Calories

[Link]()

[Link](df['Duration'], df['Calories'], color='tomato', edgecolors='black', alpha=0.7)

[Link]("Duration")

[Link]("Calories")

[Link]("Duration vs Calories")

[Link](True, linestyle='--', alpha=0.5)

[Link]()

# Pulse vs Calories

[Link]()

[Link](df['Pulse'], df['Calories'], color='steelblue', edgecolors='black', alpha=0.7)

[Link]("Pulse")

[Link]("Calories")

[Link]("Pulse vs Calories")

[Link](True, linestyle='--', alpha=0.5)

[Link]()
print("\nCleaned Data:\n", [Link]())

You might also like