Data Visualization Python Basics
Week 7
Data Visualization using python
Week 7: Data Visualization Using Python
Data visualization in Python is primarily done using Matplotlib and Pandas’ built-in plotting
functionalities. This week covers how to create and customize plots using these libraries.
1. Setting Up for Visualization
Before starting with plotting, the required libraries need to be imported:
python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
Additionally, in Jupyter Notebook, `%matplotlib notebook` can be used to enable interactive plotting.
2. Creating Simple Plots
2.1 Generating Data
To create a basic plot, data must be defined. For instance:
python
x = np.arange(10)
y = np.sin(x)
plt.plot(x, y)
plt.show()
This generates a simple line plot of the sine function.
3. Figure and Subplots
Plots are contained within a figure object, which allows multiple subplots to be placed within it.
3.1 Creating a Figure Object
python
fig = plt.figure()
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/3
This creates an empty figure. Subplots can be added using:
python
ax1 = fig.add_subplot(2, 2, 1) # (rows, columns, index)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
plt.show()
This will create a 2×2 grid of subplots, where each subplot can have its own graph.
4. Pandas’ Built-in Visualization
Pandas’ `plot()` function can quickly generate different types of plots from DataFrames.
4.1 Line Plot
python
df = pd.DataFrame(np.random.randn(10, 4), columns=list("ABCD"))
df.plot()
plt.show()
Each column is plotted as a separate line.
4.2 Bar Plot
python
df.plot.bar()
plt.show()
This generates a bar plot where each column is represented as bars.
5. Customizing Plots
Matplotlib allows customization of title, labels, legends, colors, and more.
5.1 Adding Title and Labels
python
plt.plot(x, y, label="Sine Curve", color='red', linestyle='--')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Sine Wave Plot")
plt.legend()
plt.show()
5.2 Changing Styles
Matplotlib offers different styles, e.g.,
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/3
python
plt.style.use("ggplot")
Other options include `"seaborn"`, `"fivethirtyeight"`, and `"classic"`.
6. Conclusion
This module covered essential Matplotlib and Pandas visualization techniques, including basic plots,
figure handling, subplots, and styling.
Sources
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/3