Three Fundamental Steps in Python Visualization
Data visualziation in Python typically follows three key stages:
- Determine the problem and choose the right plot type
- Prepare and transform data
- Customize parameters for clarity
Commonly Used Visualization Libraries
- Matplotlib: The foundational plotting library in Python, ideal for basic visualizations.
- Seaborn: Built on top of Matplotlib, it simplifies creating complex visualizations for data mining and machine learning tasks.
- Bokeh: Enables interactive visualizations in web browsers.
- Mapbox: Useful for advanced geospatial visualizations.
Step 1: Define the Problem and Choose the Right Visualization
Clarify the message you want to convey with your data. Different relationships in data require different visual representations:
- Points: Scatter plots for 2D data relationships
- Lines: Line plots for time-series data
- Bars: Bar charts for categorical comparisons
- Colors: Heatmaps for showing a third dimension
Step 2: Data Transformation and Function Application
Data preparation is crucial for visualization. Common data transformation techniques include:
- Merging data:
merge,concat - Reshaping data:
pivot,reshape - Removing duplicates:
drop_duplicates - Mapping values:
map - Filling missing values:
fillna - Renaming indices:
rename
Step 3: Customize Parameters for Better Readability
Enhance your plots by adjusting visual elements:
- Color:
color - Line style:
linestyle - Markers:
marker - Title:
set_title - Axis labels:
set_xlabel,set_ylabel - Legend:
legend
Basic Plotting with Matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Creating Figures and Subplots
fig = plt.figure(figsize=(10, 6))
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.2, hspace=0.3)
Styling Lines and Markers
plt.plot(np.random.randn(30), color='g', linestyle='--', marker='o')
Customizing Axes
fig, ax = plt.subplots()
ax.plot(np.random.randn(1000).cumsum())
ax.set_xticks([0, 250, 500, 750, 1000])
ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'])
ax.set_title('My First Plot')
ax.set_xlabel('Stage')
Adding Legends and Annotations
fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(np.random.randn(1000).cumsum(), 'k', label='one')
ax.plot(np.random.randn(1000).cumsum(), 'k--', label='two')
ax.plot(np.random.randn(1000).cumsum(), 'k.', label='three')
ax.legend(loc='best')
Adding Text Annotations
plt.plot(np.random.randn(1000).cumsum())
plt.text(600, 10, 'test', family='monospace', fontsize=10)
Saving Plots to Files
plt.savefig('./plot.jpg', dpi=300, bbox_inches='tight')
Plotting with Pandas
Pandas provides high-level wrappers around Matplotlib functions, simplifying the plotting process.
Line Plots
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
s.plot()
df = pd.DataFrame(np.random.randn(10, 4).cumsum(0), columns=['A', 'B', 'C', 'D'])
df.plot()
Bar Charts
fig, axes = plt.subplots(2, 1)
data = pd.Series(np.random.rand(10), index=list('abcdefghij'))
data.plot(kind='bar', ax=axes[0], rot=0, alpha=0.3)
data.plot(kind='barh', ax=axes[1], grid=True)