0% found this document useful (0 votes)
35 views10 pages

Week 3.1 (PAI)

The document discusses various types of graphs that can be created in Python using the matplotlib library for data visualization. It provides code examples for creating basic and customized bar graphs, line graphs, pie charts, scatter plots, and histograms. The examples demonstrate how to visualize one-dimensional and multi-dimensional data, compare multiple data groups, and customize the appearance of graphs.

Uploaded by

misbahrajpoot606
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)
35 views10 pages

Week 3.1 (PAI)

The document discusses various types of graphs that can be created in Python using the matplotlib library for data visualization. It provides code examples for creating basic and customized bar graphs, line graphs, pie charts, scatter plots, and histograms. The examples demonstrate how to visualize one-dimensional and multi-dimensional data, compare multiple data groups, and customize the appearance of graphs.

Uploaded by

misbahrajpoot606
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
You are on page 1/ 10

Plo$ng in Python

In Python, graphs created using the matplotlib library provide a versatile means of visualizing data,
relationships, and trends. With matplotlib's robust plotting capabilities, developers can generate
various types of graphs, including line plots, scatter plots, bar charts, histograms, and more. These
graphs serve as powerful tools for analyzing datasets, exploring patterns, and communicating
insights effectively. With matplotlib's intuitive interface and extensive customization options, users
can create visually appealing graphs tailored to their specific needs, making it a go-to choice for
data visualization tasks in Python.

Bar Graph

Simple Bar Graph


This example demonstrates a basic bar graph using matplotlib in Python. It displays categories on
the x-axis and corresponding values on the y-axis.

import matplotlib.pyplot as plt

# Data
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]

# Plot
plt.bar(categories, values)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Simple Bar Graph')
plt.show()

Horizontal Bar Graph


This example illustrates a horizontal bar graph where categories are shown on the y-axis and values
on the x-axis. It's useful when you have long category names or want to emphasize the values.

import matplotlib.pyplot as plt

# Data
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]

# Plot
plt.barh(categories, values)
plt.xlabel('Values')
plt.ylabel('Categories')
plt.title('Horizontal Bar Graph')
plt.show()
Grouped Bar Graph
This example shows a grouped bar graph where values from two different groups are displayed
side by side for each category. It's suitable for comparing values across multiple groups within the
same categories.

import numpy as np
import matplotlib.pyplot as plt

# Data
categories = ['A', 'B', 'C', 'D', 'E']
values1 = [23, 45, 56, 78, 32]
values2 = [40, 35, 60, 55, 25]

# Plot
x = np.arange(len(categories))
width = 0.35

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, values1, width, label='Group 1')
rects2 = ax.bar(x + width/2, values2, width, label='Group 2')

ax.set_xlabel('Categories')
ax.set_ylabel('Values')
ax.set_title('Grouped Bar Graph')
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()

plt.show()

Stacked Bar Graph


Here, a stacked bar graph is depicted where values from different groups are stacked on top of
each other for each category. It's useful for showcasing the total value along with the contribution
of each group.

import matplotlib.pyplot as plt

# Data
categories = ['A', 'B', 'C', 'D', 'E']
values1 = [23, 45, 56, 78, 32]
values2 = [40, 35, 60, 55, 25]

# Plot
plt.bar(categories, values1, label='Group 1')
plt.bar(categories, values2, bottom=values1, label='Group 2')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Stacked Bar Graph')
plt.legend()
plt.show()

Colored Bar Graph


This example adds color customization to the simple bar graph. Each bar is assigned a specific
color from a predefined list, making it visually appealing and aiding in distinguishing between
categories.

import matplotlib.pyplot as plt

# Data
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]
colors = ['red', 'blue', 'green', 'orange', 'purple']

# Plot
plt.bar(categories, values, color=colors)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Colored Bar Graph')
plt.show()

Line Graph

Simple Line Graph


This example illustrates a basic line graph where data points are connected by straight
lines. It's useful for showing the trend or progression of data over a continuous range.

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]

# Plot
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Graph')
plt.show()
Line Graph with Mul:ple Lines
This example demonstrates a line graph with multiple lines, each representing a
different dataset. It's useful for comparing trends or patterns between different sets of
data.

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 25, 30, 35]
y2 = [15, 18, 22, 27, 32]

# Plot
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Graph with Multiple Lines')
plt.legend()
plt.show()

Line Graph with Markers


This example adds markers to data points in the line graph, making it easier to identify
individual data points. It's useful when you want to emphasize specific data points
within the graph.

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]

# Plot
plt.plot(x, y, marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Graph with Markers')
plt.show()

Line Graph with Customiza:on


This example showcases a line graph with customized appearance, including line color,
style, and marker size. It's useful for creating visually appealing graphs tailored to
specific preferences or requirements.
import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]

# Plot
plt.plot(x, y, color='green', linestyle='--', marker='o', markersize=8)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Graph with Customization')
plt.show()

Pie Chart

Simple Pie Chart


This example demonstrates a basic pie chart where each category (label) is represented by a slice,
with the size of each slice proportional to its corresponding value. It's useful for displaying the
distribution of categorical data as parts of a whole.

import matplotlib.pyplot as plt

# Data
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

# Plot
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('Simple Pie Chart')
plt.show()

Exploded Pie Chart


This example adds an 'explosion' effect to one of the slices in the pie chart to emphasize its
significance. It's useful for highlighting specific categories within the dataset.

import matplotlib.pyplot as plt

# Data
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # "explode" the 2nd slice (B)

# Plot
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%')
plt.title('Exploded Pie Chart')
plt.show()
Pie Chart with Custom Colors
This example customizes the colors of the pie chart slices to make the visualization more visually
appealing or to convey additional information. It's useful for enhancing the aesthetics of the chart
or for emphasizing specific categories.

import matplotlib.pyplot as plt

# Data
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['red', 'blue', 'green', 'orange']

# Plot
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
plt.title('Pie Chart with Custom Colors')
plt.show()

Nested Pie Chart


This example showcases a nested pie chart where smaller pies representing sub-categories are
nested within larger pies representing main categories. It's useful for visualizing hierarchical data
structures or nested relationships within the dataset.

import matplotlib.pyplot as plt

# Data
labels_outer = ['Group 1', 'Group 2']
sizes_outer = [60, 40]
labels_inner = ['A', 'B', 'C', 'D']
sizes_inner = [20, 15, 25, 40]

# Plot
fig, ax = plt.subplots()
ax.pie(sizes_outer, labels=labels_outer, radius=1.2)
ax.pie(sizes_inner, labels=labels_inner, radius=0.7)
plt.title('Nested Pie Chart')
plt.show()

Sca1er Graph

Simple Sca@er Plot


This example demonstrates a basic scatter plot where individual data points are represented as
markers on a 2D plane. It's useful for visualizing the relationship between two variables and
identifying patterns or trends within the data.
import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [10, 15, 20, 25, 30]

# Plot
plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Scatter Plot')
plt.show()

Sca@er Plot with Different Colors and Sizes


This example customizes the appearance of markers in the scatter plot by varying their sizes and
colors based on additional data variables. It's useful for highlighting different characteristics of
data points within the plot.

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [10, 15, 20, 25, 30]
sizes = [100, 200, 300, 400, 500]
colors = ['red', 'blue', 'green', 'orange', 'purple']

# Plot
plt.scatter(x, y, s=sizes, c=colors, alpha=0.5)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot with Different Colors and Sizes')
plt.show()

Sca@er Plot with Regression Line


This example adds a regression line to the scatter plot to visualize the linear relationship between
two variables. It's useful for estimating the trend or direction of the relationship between the
variables.

import matplotlib.pyplot as plt


import numpy as np

# Data
x = [1, 2, 3, 4, 5]
y = [10, 15, 20, 25, 30]

# Fit a linear regression line


slope, intercept = np.polyfit(x, y, 1)
fit_line = [slope * i + intercept for i in x]
# Plot
plt.scatter(x, y)
plt.plot(x, fit_line, color='red')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot with Regression Line')
plt.show()

Sca@er Plot with Annota:on


This example annotates each data point in the scatter plot with its corresponding value, making it
easier to identify specific data points. It's useful for adding additional information or context to
individual data points within the plot.

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [10, 15, 20, 25, 30]

# Plot
plt.scatter(x, y)
for i, txt in enumerate(y):
plt.annotate(txt, (x[i], y[i]))
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot with Annotation')
plt.show()

Histogram
A histogram is a graphical representation of the distribution of numerical data. It consists of a
series of adjacent rectangles, or bins, where each bin represents a specific range of values. The
height of each bin corresponds to the frequency or count of data points falling within that range.
Histograms provide a visual summary of the underlying data distribution, allowing for quick
insights into the central tendency, spread, and shape of the dataset. They are commonly used in
data analysis and visualization to identify patterns, outliers, and underlying trends within the data.

What is Bin?

In histograms, bins represent intervals into which the data range is divided. Each bin corresponds
to a specific range of values, and the height of the bar within each bin represents the frequency or
count of data points falling within that range. Choosing an appropriate number of bins is crucial
as it determines the granularity of the histogram; too few bins may oversimplify the data
distribution, while too many bins may introduce noise or obscure underlying patterns. Adjusting
the bin size allows for a balance between capturing important details of the data distribution and
maintaining clarity in visualization.

Simple Histogram
This example illustrates a basic histogram where the distribution of a single dataset is represented
by bars. It's useful for visualizing the frequency or distribution of values within a continuous
variable.

import matplotlib.pyplot as plt


import numpy as np

# Data
data = np.random.normal(loc=0, scale=1, size=1000)

# Plot
plt.hist(data, bins=30)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Simple Histogram')
plt.show()

Histogram with Custom Bins


This example customizes the bin sizes in the histogram, allowing for a more detailed or specific
representation of the data distribution. It's useful for focusing on particular ranges or intervals
within the dataset.

import matplotlib.pyplot as plt


import numpy as np

# Data
data = np.random.normal(loc=0, scale=1, size=1000)

# Plot
plt.hist(data, bins=[-3, -2, -1, 0, 1, 2, 3])
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram with Custom Bins')
plt.show()

Overlayed Histograms
This example overlays multiple histograms, each representing a different dataset, on the same plot.
It's useful for comparing the distributions of multiple variables or datasets within the same plot.

import matplotlib.pyplot as plt


import numpy as np
# Data
data1 = np.random.normal(loc=0, scale=1, size=1000)
data2 = np.random.normal(loc=2, scale=1, size=1000)

# Plot
plt.hist(data1, bins=30, alpha=0.5, label='Data 1')
plt.hist(data2, bins=30, alpha=0.5, label='Data 2')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Overlayed Histograms')
plt.legend()
plt.show()

Histogram with Density Plot


This example combines a histogram with a kernel density estimate (KDE) plot, providing a
smoother representation of the data distribution. It's useful for visualizing the probability density
function of the underlying data.

import matplotlib.pyplot as plt


import seaborn as sns
import numpy as np

# Data
data = np.random.normal(loc=0, scale=1, size=1000)

# Plot
sns.histplot(data, kde=True)
plt.xlabel('Value')
plt.ylabel('Density')
plt.title('Histogram with Density Plot')
plt.show()

You might also like